diff --git a/documentation/azure-powershell-modules.md b/documentation/azure-powershell-modules.md index a3b5481c599d..e372a790d79f 100644 --- a/documentation/azure-powershell-modules.md +++ b/documentation/azure-powershell-modules.md @@ -27,9 +27,12 @@ Blueprints | `Az.Blueprint` Content Delivery Network | `Az.Cdn` | [![Cdn]][CdnGallery] Cognitive Services | `Az.CognitiveServices` | [![CognitiveServices]][CognitiveServicesGallery] Compute | `Az.Compute` | [![Compute]][ComputeGallery] +Connected Kubernetes | `Az.ConnectedKubernetes` | [![ConnectedKubernetes]][ConnectedKubernetesGallery] + Container Instance | `Az.ContainerInstance` | [![ContainerInstance]][ContainerInstanceGallery] Container Registry | `Az.ContainerRegistry` | [![ContainerRegistry]][ContainerRegistryGallery] Cosmos DB | `Az.CosmosDB` | [![CosmosDB]][CosmosDBGallery] +Custom Resource Providers | `Az.CustomProviders` | [![CustomProviders]][CustomProvidersGallery] Data Box | `Az.DataBox` | [![DataBox]][DataBoxGallery] Data Box Edge (Stack Edge) | `Az.DataBoxEdge` | [![DataBoxEdge]][DataBoxEdgeGallery] Databricks | `Az.Databricks` | [![Databricks]][DatabricksGallery] @@ -49,6 +52,7 @@ Event Hubs | `Az.EventHub` Front Door | `Az.FrontDoor` | [![FrontDoor]][FrontDoorGallery] Functions | `Az.Functions` | [![Functions]][FunctionsGallery] Guest Configuration | `Az.GuestConfiguration` | [![GuestConfiguration]][GuestConfigurationGallery] +SAP HANA on Azure | `Az.HanaOnAzure` | [![HanaOnAzure]][HanaOnAzureGallery] HDInsight | `Az.HDInsight` | [![HDInsight]][HDInsightGallery] API for FHIR | `Az.HealthcareApis` | [![HealthcareApis]][HealthcareApisGallery] HPC Cache | `Az.HPCCache` | [![HPCCache]][HPCCacheGallery] @@ -57,6 +61,7 @@ Import/Export | `Az.ImportExport` IoT Central | `Az.IotCentral` | [![IotCentral]][IotCentralGallery] IoT Hub | `Az.IotHub` | [![IotHub]][IotHubGallery] Key Vault | `Az.KeyVault` | [![KeyVault]][KeyVaultGallery] +Kubernetes Configuration | `Az.KubernetesConfiguration` | [![KubernetesConfiguration]][KubernetesConfigurationGallery] Kusto | `Az.Kusto` | [![Kusto]][KustoGallery] Logic App | `Az.LogicApp` | [![LogicApp]][LogicAppGallery] Machine Learning | `Az.MachineLearning` | [![MachineLearning]][MachineLearningGallery] @@ -71,6 +76,7 @@ Marketplace Ordering | `Az.MarketplaceOrdering` Media | `Az.Media` | [![Media]][MediaGallery] Mixed Reality | `Az.MixedReality` | [![MixedReality]][MixedRealityGallery] Monitor | `Az.Monitor` | [![Monitor]][MonitorGallery] +Monitoring Solutions | `Az.MonitoringSolutions` | [![MonitoringSolutions]][MonitoringSolutionsGallery] Database for MySQL | `Az.MySql` | [![MySql]][MySqlGallery] NetApp Files | `Az.NetAppFiles` | [![NetAppFiles]][NetAppFilesGallery] Network | `Az.Network` | [![Network]][NetworkGallery] @@ -127,9 +133,11 @@ Web App Service | `Az.Websites` [Cdn]: https://img.shields.io/powershellgallery/v/Az.Cdn.svg?style=flat-square&label=Az.Cdn [CognitiveServices]: https://img.shields.io/powershellgallery/v/Az.CognitiveServices.svg?style=flat-square&label=Az.CognitiveServices [Compute]: https://img.shields.io/powershellgallery/v/Az.Compute.svg?style=flat-square&label=Az.Compute +[ConnectedKubernetes]: https://img.shields.io/powershellgallery/v/Az.ConnectedKubernetes.svg?style=flat-square&label=Az.ConnectedKubernetes [ContainerInstance]: https://img.shields.io/powershellgallery/v/Az.ContainerInstance.svg?style=flat-square&label=Az.ContainerInstance [ContainerRegistry]: https://img.shields.io/powershellgallery/v/Az.ContainerRegistry.svg?style=flat-square&label=Az.ContainerRegistry [CosmosDB]: https://img.shields.io/powershellgallery/v/Az.CosmosDB.svg?style=flat-square&label=Az.CosmosDB +[CustomProvidersDB]: https://img.shields.io/powershellgallery/v/Az.CustomProviders.svg?style=flat-square&label=Az.CustomProviders [DataBox]: https://img.shields.io/powershellgallery/v/Az.DataBox.svg?style=flat-square&label=Az.DataBox [DataBoxEdge]: https://img.shields.io/powershellgallery/v/Az.DataBoxEdge.svg?style=flat-square&label=Az.DataBoxEdge [Databricks]: https://img.shields.io/powershellgallery/v/Az.Databricks.svg?style=flat-square&label=Az.Databricks @@ -149,6 +157,7 @@ Web App Service | `Az.Websites` [FrontDoor]: https://img.shields.io/powershellgallery/v/Az.FrontDoor.svg?style=flat-square&label=Az.FrontDoor [Functions]: https://img.shields.io/powershellgallery/v/Az.Functions.svg?style=flat-square&label=Az.Functions [GuestConfiguration]: https://img.shields.io/powershellgallery/v/Az.GuestConfiguration.svg?style=flat-square&label=Az.GuestConfiguration +[HanaOnAzure]: https://img.shields.io/powershellgallery/v/Az.HanaOnAzure.svg?style=flat-square&label=Az.HanaOnAzure [HDInsight]: https://img.shields.io/powershellgallery/v/Az.HDInsight.svg?style=flat-square&label=Az.HDInsight [HealthcareApis]: https://img.shields.io/powershellgallery/v/Az.HealthcareApis.svg?style=flat-square&label=Az.HealthcareApis [HPCCache]: https://img.shields.io/powershellgallery/v/Az.HPCCache.svg?style=flat-square&label=Az.HPCCache @@ -157,6 +166,7 @@ Web App Service | `Az.Websites` [IotCentral]: https://img.shields.io/powershellgallery/v/Az.IotCentral.svg?style=flat-square&label=Az.IotCentral [IotHub]: https://img.shields.io/powershellgallery/v/Az.IotHub.svg?style=flat-square&label=Az.IotHub [KeyVault]: https://img.shields.io/powershellgallery/v/Az.KeyVault.svg?style=flat-square&label=Az.KeyVault +[KubernetesConfiguration]: https://img.shields.io/powershellgallery/v/Az.KubernetesConfiguration.svg?style=flat-square&label=Az.KubernetesConfiguration [Kusto]: https://img.shields.io/powershellgallery/v/Az.Kusto.svg?style=flat-square&label=Az.Kusto [LogicApp]: https://img.shields.io/powershellgallery/v/Az.LogicApp.svg?style=flat-square&label=Az.LogicApp [MachineLearning]: https://img.shields.io/powershellgallery/v/Az.MachineLearning.svg?style=flat-square&label=Az.MachineLearning @@ -171,6 +181,7 @@ Web App Service | `Az.Websites` [Media]: https://img.shields.io/powershellgallery/v/Az.Media.svg?style=flat-square&label=Az.Media [MixedReality]: https://img.shields.io/powershellgallery/v/Az.MixedReality.svg?style=flat-square&label=Az.MixedReality [Monitor]: https://img.shields.io/powershellgallery/v/Az.Monitor.svg?style=flat-square&label=Az.Monitor +[MonitoringSolutions]: https://img.shields.io/powershellgallery/v/Az.MonitoringSolutions.svg?style=flat-square&label=Az.MonitoringSolutions [MySql]: https://img.shields.io/powershellgallery/v/Az.MySql.svg?style=flat-square&label=Az.MySql [NetAppFiles]: https://img.shields.io/powershellgallery/v/Az.NetAppFiles.svg?style=flat-square&label=Az.NetAppFiles [Network]: https://img.shields.io/powershellgallery/v/Az.Network.svg?style=flat-square&label=Az.Network @@ -225,9 +236,11 @@ Web App Service | `Az.Websites` [CdnGallery]: https://www.powershellgallery.com/packages/Az.Cdn/ [CognitiveServicesGallery]: https://www.powershellgallery.com/packages/Az.CognitiveServices/ [ComputeGallery]: https://www.powershellgallery.com/packages/Az.Compute/ +[ConnectedKubernetesGallery]: https://www.powershellgallery.com/packages/Az.ConnectedKubernetes/ [ContainerInstanceGallery]: https://www.powershellgallery.com/packages/Az.ContainerInstance/ [ContainerRegistryGallery]: https://www.powershellgallery.com/packages/Az.ContainerRegistry/ [CosmosDBGallery]: https://www.powershellgallery.com/packages/Az.CosmosDB/ +[CustomProvidersGallery]: https://www.powershellgallery.com/packages/Az.CustomProviders/ [DataBoxGallery]: https://www.powershellgallery.com/packages/Az.DataBox/ [DataBoxEdgeGallery]: https://www.powershellgallery.com/packages/Az.DataBoxEdge/ [DatabricksGallery]: https://www.powershellgallery.com/packages/Az.Databricks/ @@ -247,6 +260,7 @@ Web App Service | `Az.Websites` [FrontDoorGallery]: https://www.powershellgallery.com/packages/Az.FrontDoor/ [FunctionsGallery]: https://www.powershellgallery.com/packages/Az.Functions/ [GuestConfigurationGallery]: https://www.powershellgallery.com/packages/Az.GuestConfiguration/ +[HanaOnAzureGallery]: https://www.powershellgallery.com/packages/Az.HanaOnAzure/ [HDInsightGallery]: https://www.powershellgallery.com/packages/Az.HDInsight/ [HealthcareApisGallery]: https://www.powershellgallery.com/packages/Az.HealthcareApis/ [HPCCacheGallery]: https://www.powershellgallery.com/packages/Az.HPCCache/ @@ -255,6 +269,7 @@ Web App Service | `Az.Websites` [IotCentralGallery]: https://www.powershellgallery.com/packages/Az.IotCentral/ [IotHubGallery]: https://www.powershellgallery.com/packages/Az.IotHub/ [KeyVaultGallery]: https://www.powershellgallery.com/packages/Az.KeyVault/ +[KubernetesConfigurationGallery]: https://www.powershellgallery.com/packages/Az.KubernetesConfiguration/ [KustoGallery]: https://www.powershellgallery.com/packages/Az.Kusto/ [LogicAppGallery]: https://www.powershellgallery.com/packages/Az.LogicApp/ [MachineLearningGallery]: https://www.powershellgallery.com/packages/Az.MachineLearning/ @@ -269,6 +284,7 @@ Web App Service | `Az.Websites` [MediaGallery]: https://www.powershellgallery.com/packages/Az.Media/ [MixedRealityGallery]: https://www.powershellgallery.com/packages/Az.MixedReality/ [MonitorGallery]: https://www.powershellgallery.com/packages/Az.Monitor/ +[MonitoringSolutionsGallery]: https://www.powershellgallery.com/packages/Az.MonitoringSolutions/ [MySqlGallery]: https://www.powershellgallery.com/packages/Az.MySql/ [NetAppFilesGallery]: https://www.powershellgallery.com/packages/Az.NetAppFiles/ [NetworkGallery]: https://www.powershellgallery.com/packages/Az.Network/ diff --git a/src/ConnectedKubernetes/Az.ConnectedKubernetes.csproj b/src/ConnectedKubernetes/Az.ConnectedKubernetes.csproj new file mode 100644 index 000000000000..dc9d6760fd68 --- /dev/null +++ b/src/ConnectedKubernetes/Az.ConnectedKubernetes.csproj @@ -0,0 +1,7 @@ + + + ConnectedKubernetes + + + + \ No newline at end of file diff --git a/src/ConnectedKubernetes/Az.ConnectedKubernetes.format.ps1xml b/src/ConnectedKubernetes/Az.ConnectedKubernetes.format.ps1xml new file mode 100644 index 000000000000..abea45198d67 --- /dev/null +++ b/src/ConnectedKubernetes/Az.ConnectedKubernetes.format.ps1xml @@ -0,0 +1,477 @@ + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.ConnectedKubernetesIdentity + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.ConnectedKubernetesIdentity + + + + + + + + + + + + + + + + + + ClusterName + + + ResourceGroupName + + + SubscriptionId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedCluster + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedCluster + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfile + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfile + + + + + + + + + + + + + + + + + + ClientAppId + + + ServerAppId + + + TenantId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterIdentity + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterIdentity + + + + + + + + + + + + + + + + + + PrincipalId + + + TenantId + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterList + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterList + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchProperties + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchProperties + + + + + + + + + + + + AgentPublicKeyCertificate + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchTags + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterProperties + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterProperties + + + + + + + + + + + + + + + + + + + + + + + + AgentPublicKeyCertificate + + + AgentVersion + + + KubernetesVersion + + + ProvisioningState + + + TotalNodeCount + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.CredentialResult + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.CredentialResult + + + + + + + + + + + + + + + Name + + + Value + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorDetails + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorDetails + + + + + + + + + + + + + + + Code + + + Message + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.Operation + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.Operation + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationDisplay + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationDisplay + + + + + + + + + + + + + + + + + + + + + Description + + + Operation + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationList + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationList + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.Resource + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.Resource + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResource + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResource + + + + + + + + + + + + + + + + + + Name + + + Type + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTags + + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTags + + + + + + + + + + + + Item + + + + + + + + \ No newline at end of file diff --git a/src/ConnectedKubernetes/Az.ConnectedKubernetes.psd1 b/src/ConnectedKubernetes/Az.ConnectedKubernetes.psd1 new file mode 100644 index 000000000000..11f80d725ca7 --- /dev/null +++ b/src/ConnectedKubernetes/Az.ConnectedKubernetes.psd1 @@ -0,0 +1,25 @@ +@{ + GUID = '59df8ab1-442a-41ae-9b55-60b505bae789' + RootModule = './Az.ConnectedKubernetes.psm1' + ModuleVersion = '0.1.0' + CompatiblePSEditions = 'Core', 'Desktop' + Author = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' + Copyright = 'Microsoft Corporation. All rights reserved.' + Description = 'Microsoft Azure PowerShell: ConnectedKubernetes cmdlets' + PowerShellVersion = '5.1' + DotNetFrameworkVersion = '4.7.2' + RequiredAssemblies = './bin/Az.ConnectedKubernetes.private.dll' + RequiredModules = @(@{ModuleName = 'Az.Accounts'; ModuleVersion = '1.9.0'; }) + FormatsToProcess = './Az.ConnectedKubernetes.format.ps1xml' + FunctionsToExport = 'Get-AzConnectedKubernetes', 'New-AzConnectedKubernetes', 'Remove-AzConnectedKubernetes', 'Update-AzConnectedKubernetes' + AliasesToExport = '*' + PrivateData = @{ + PSData = @{ + Tags = 'Azure', 'ResourceManager', 'ARM', 'PSModule', 'ConnectedKubernetes' + LicenseUri = 'https://aka.ms/azps-license' + ProjectUri = 'https://github.com/Azure/azure-powershell' + ReleaseNotes = '* the first preview release' + } + } +} diff --git a/src/ConnectedKubernetes/Az.ConnectedKubernetes.psm1 b/src/ConnectedKubernetes/Az.ConnectedKubernetes.psm1 new file mode 100644 index 000000000000..52bc33e74f63 --- /dev/null +++ b/src/ConnectedKubernetes/Az.ConnectedKubernetes.psm1 @@ -0,0 +1,109 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # + # Copyright Microsoft Corporation + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # http://www.apache.org/licenses/LICENSE-2.0 + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'1.7.4' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 1.7.4 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 1.7.4 or greater. For installation instructions, please see: https://docs.microsoft.com/en-us/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'1.7.4') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 1.7.4 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to remove '.PSSharedModules' in your home directory. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.ConnectedKubernetes.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.ConnectedKubernetes.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/ConnectedKubernetes/ChangeLog.md b/src/ConnectedKubernetes/ChangeLog.md new file mode 100644 index 000000000000..b76ecb79cf4a --- /dev/null +++ b/src/ConnectedKubernetes/ChangeLog.md @@ -0,0 +1,24 @@ + +## Upcoming Release + +## Version 0.1.0 +* the first preview release + diff --git a/src/ConnectedKubernetes/ConnectedKubernetes.sln b/src/ConnectedKubernetes/ConnectedKubernetes.sln new file mode 100644 index 000000000000..709176957217 --- /dev/null +++ b/src/ConnectedKubernetes/ConnectedKubernetes.sln @@ -0,0 +1,48 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Accounts", "..\Accounts\Accounts\Accounts.csproj", "{142D7B0B-388A-4CEB-A228-7F6D423C5C2E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication", "..\Accounts\Authentication\Authentication.csproj", "{62843FE6-7575-4D88-B989-7DF7EEC0BC01}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication.ResourceManager", "..\Accounts\Authentication.ResourceManager\Authentication.ResourceManager.csproj", "{442C609B-A431-4A71-B289-08F0B63C83E5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authenticators", "..\Accounts\Authenticators\Authenticators.csproj", "{59E8F6B8-8F0E-403F-B88B-9736DBC396D9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Az.ConnectedKubernetes", "Az.ConnectedKubernetes.csproj", "{1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.Build.0 = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.Build.0 = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.Build.0 = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.Build.0 = Release|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F9B3D96E-9680-40BE-A917-02EE655D6030} + EndGlobalSection +EndGlobal diff --git a/src/ConnectedKubernetes/MSSharedLibKey.snk b/src/ConnectedKubernetes/MSSharedLibKey.snk new file mode 100644 index 000000000000..695f1b38774e Binary files /dev/null and b/src/ConnectedKubernetes/MSSharedLibKey.snk differ diff --git a/src/ConnectedKubernetes/Properties/AssemblyInfo.cs b/src/ConnectedKubernetes/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..3d8b538cdd3c --- /dev/null +++ b/src/ConnectedKubernetes/Properties/AssemblyInfo.cs @@ -0,0 +1,28 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Microsoft Azure Powershell - ConnectedKubernetes")] +[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] +[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] +[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] + +[assembly: ComVisible(false)] +[assembly: CLSCompliant(false)] +[assembly: Guid("CE93AF3C-92E0-4357-93A0-22A5766CDF13")] +[assembly: AssemblyVersion("0.1.0")] +[assembly: AssemblyFileVersion("0.1.0")] \ No newline at end of file diff --git a/src/ConnectedKubernetes/build-module.ps1 b/src/ConnectedKubernetes/build-module.ps1 new file mode 100644 index 000000000000..de0123a884d1 --- /dev/null +++ b/src/ConnectedKubernetes/build-module.ps1 @@ -0,0 +1,153 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $Isolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.ConnectedKubernetes' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: ConnectedKubernetes cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.ConnectedKubernetes.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/src/ConnectedKubernetes/check-dependencies.ps1 b/src/ConnectedKubernetes/check-dependencies.ps1 new file mode 100644 index 000000000000..5cd7ab5c808f --- /dev/null +++ b/src/ConnectedKubernetes/check-dependencies.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '1.7.4' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -versionMinimum '' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and (-not (Test-Path -Path $resourceModule))) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest-beta .\readme.md --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/src/ConnectedKubernetes/custom/Az.ConnectedKubernetes.custom.psm1 b/src/ConnectedKubernetes/custom/Az.ConnectedKubernetes.custom.psm1 new file mode 100644 index 000000000000..98305bb3def3 --- /dev/null +++ b/src/ConnectedKubernetes/custom/Az.ConnectedKubernetes.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '../bin/Az.ConnectedKubernetes.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '../internal/Az.ConnectedKubernetes.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/ConnectedKubernetes/custom/New-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/custom/New-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..e0832426fb6e --- /dev/null +++ b/src/ConnectedKubernetes/custom/New-AzConnectedKubernetes.ps1 @@ -0,0 +1,273 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to register a new K8s cluster and thereby create a tracked resource in ARM +.Description +API to register a new K8s cluster and thereby create a tracked resource in ARM + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/new-azconnectedkubernetes +#> +function New-AzConnectedKubernetes { + [OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] + [CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] + param( + [Parameter(Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group to which the kubernetes cluster is registered. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the subscription to which the kubernetes cluster is registered. + ${SubscriptionId}, + + [Parameter(HelpMessage="Path to the kube config file")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Path to the kube config file + ${KubeConfig}, + + [Parameter(HelpMessage="Kubconfig context from current machine")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Kubconfig context from current machine + ${KubeContext}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Location of the cluster + ${Location}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} + ) + + process { + if ($PSBoundParameters.ContainsKey('KubeConfig')) { + $Null = $PSBoundParameters.Remove('KubeConfig') + } elseif (Test-Path Env:KUBECONFIG) { + $KubeConfig = Get-ChildItem -Path Env:KUBECONFIG + } elseif (Test-Path Env:Home) { + $KubeConfig = Join-Path -Path $Env:Home -ChildPath '.kube' | Join-Path -ChildPath 'config' + } else { + $KubeConfig = Join-Path -Path $Home -ChildPath '.kube' | Join-Path -ChildPath 'config' + } + if (-not (Test-Path $KubeConfig)) { + Write-Error 'Cannot find the kube-config. Please make sure that you have the kube-config on your machine.' + return + } + if ($PSBoundParameters.ContainsKey('KubeContext')) { + $Null = $PSBoundParameters.Remove('KubeContext') + } + if (($KubeContext -eq $null) -or ($KubeContext -eq '')) { + $KubeContext = kubectl config current-context + } + + $CommonPSBoundParameters = @{} + if ($PSBoundParameters.ContainsKey('HttpPipelineAppend')) { + $CommonPSBoundParameters['HttpPipelineAppend'] = $HttpPipelineAppend + } + if ($PSBoundParameters.ContainsKey('HttpPipelinePrepend')) { + $CommonPSBoundParameters['HttpPipelinePrepend'] = $HttpPipelinePrepend + } + if ($PSBoundParameters.ContainsKey('SubscriptionId')) { + $CommonPSBoundParameters['SubscriptionId'] = $SubscriptionId + } + $AadProfileClientAppId = '' + $PSBoundParameters.Add('AadProfileClientAppId', $AadProfileClientAppId) + $AadProfileServerAppId = '' + $PSBoundParameters.Add('AadProfileServerAppId', $AadProfileServerAppId) + $AadProfileTenantId = '' + $PSBoundParameters.Add('AadProfileTenantId', $AadProfileTenantId) + $IdentityType = [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType]::SystemAssigned + $PSBoundParameters.Add('IdentityType', $IdentityType) + + #Region check helm install + try { + $HelmVersion = helm version --short --kubeconfig $KubeConfig + if ($HelmVersion.Contains("v2")) { + Write-Error "Helm version 3+ is required. Ensure that you have installed the latest version of Helm. Learn more at https://aka.ms/arc/k8s/onboarding-helm-install" + return + } + } catch { + Write-Error "Helm version 3+ is required. Ensure that you have installed the latest version of Helm. Learn more at https://aka.ms/arc/k8s/onboarding-helm-install" + throw + } + #EndRegion + + #Region get release namespace + $ReleaseNamespace = $null + try { + $ReleaseNamespace = (helm status azure-arc -o json --kubeconfig $KubeConfig --kube-context $KubeContext | ConvertFrom-Json).namespace + } catch { + Write-Error "Fail to find the namespace for azure-arc." + } + #Endregion + + if ($null -ne $ReleaseNamespace) { + # $Configmap = kubectl get configmap --namespace azure-arc azure-clusterconfig -o json --kubeconfig $KubeConfig | ConvertFrom-Json + # $ConfigmapRgName = $Configmap.data.AZURE_RESOURCE_GROUP + # $ConfigmapClusterName = $Configmap.data.AZURE_RESOURCE_NAME + try { + $ExistConnectedKubernetes = Get-AzConnectedKubernetes -ResourceGroupName $ResourceGroupName -ClusterName $ClusterName @CommonPSBoundParameters + + $PSBoundParameters.Add('AgentPublicKeyCertificate', $ExistConnectedKubernetes.AgentPublicKeyCertificate) + Az.ConnectedKubernetes.internal\New-AzConnectedKubernetes @PSBoundParameters + # if (($ResourceGroupName -eq $ConfigmapRgName) -and ($ClusterName -eq $ConfigmapClusterName)) { + # $PSBoundParameters.Add('AgentPublicKeyCertificate', $ExistConnectedKubernetes.AgentPublicKeyCertificate) + # Az.ConnectedKubernetes.internal\New-AzConnectedKubernetes @PSBoundParameters + # } else { + # Write-Error "The kubernetes cluster you are trying to onboard is already onboarded to the resource group '${ConfigmapRgName}' with resource name '${ConfigmapClusterName}'." + # } + # return + } catch { + helm delete azure-arc --namespace $ReleaseNamespace --kubeconfig $KubeConfig --kube-context $KubeContext + } + } + + if ((Test-Path Env:HELMREPONAME) -and (Test-Path Env:HELMREPOURL)) { + $HelmRepoName = Get-ChildItem -Path Env:HELMREPONAME + $HelmRepoUrl = Get-ChildItem -Path Env:HELMREPOURL + helm repo add $HelmRepoName $HelmRepoUrl --kubeconfig $KubeConfig --kube-context $KubeContext + } + + if (Test-Path Env:HELMREGISTRY) { + $RegisteryPath = Get-ChildItem -Path Env:HELMREGISTRY + } else { + $ReleaseTrain = '' + if ((Test-Path Env:RELEASETRAIN) -and (Test-Path Env:RELEASETRAIN)) { + $ReleaseTrain = Get-ChildItem -Path Env:RELEASETRAIN + } else { + $ReleaseTrain = 'stable' + } + $ChartLocationUrl = "https://${Location}.dp.kubernetesconfiguration.azure.com/azure-arc-k8sagents/GetLatestHelmPackagePath?api-version=2019-11-01-preview&releaseTrain=${ReleaseTrain}" + + $Uri = [System.Uri]::New($ChartLocationUrl) + $Account = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext.Account + $Env = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureEnvironment]::PublicEnvironments[[Microsoft.Azure.Commands.Common.Authentication.Abstractions.EnvironmentName]::AzureCloud] + $TenantId = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext.Tenant.Id + $PromptBehavior = [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never + $Token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($account, $env, $tenantId, $null, $promptBehavior, $null) + $AccessToken = $Token.AccessToken + + $HeaderParameter = @{ + "Authorization" = "Bearer $AccessToken" + } + $Response = Invoke-WebRequest -Uri $Uri -Headers $HeaderParameter -Method Post + if ($Response.StatusCode -eq 200) { + $RegisteryPath = ($Response.Content | ConvertFrom-Json).repositoryPath + } else { + Write-Error "Error while fetching helm chart registry path: ${$Response.RawContent}" + throw + } + } + Set-Item -Path Env:HELM_EXPERIMENTAL_OCI -Value 1 + #Region pull helm chart + try { + helm chart pull $RegisteryPath --kubeconfig $KubeConfig --kube-context $KubeContext + } catch { + Write-Error "Unable to pull helm chart from the registery $RegisteryPath" + throw + } + #Endregion + + #Region export helm chart + $ChartExportPath = Join-Path -Path (Get-Item Env:HOME).Value -ChildPath '.azure' | Join-Path -ChildPath 'AzureArcCharts' + try { + helm chart export $RegisteryPath --kubeconfig $KubeConfig --kube-context $KubeContext --destination $ChartExportPath + } catch { + Write-Error "Unable to export helm chart from the registery $RegisteryPath" + throw + } + #Endregion + + $RSA = [System.Security.Cryptography.RSA]::Create(4096) + $AgentPublicKey = [System.Convert]::ToBase64String($RSA.ExportRSAPublicKey()) + $AgentPrivateKey = [System.Convert]::ToBase64String($RSA.ExportRSAPrivateKey()) + + $HelmChartPath = Join-Path -Path $ChartExportPath -ChildPath 'azure-arc-k8sagents' + if (Test-Path Env:HELMCHART) { + $ChartPath = Get-ChildItem -Path Env:HELMCHART + } else { + $ChartPath = $HelmChartPath + } + + $TenantId = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext.Tenant.Id + helm upgrade --install azure-arc $ChartPath --set global.subscriptionId=$SubscriptionId --set global.resourceGroupName=$ResourceGroupName --set global.resourceName=$ClusterName --set global.tenantId=$TenantId --set global.location=$Location --set global.onboardingPrivateKey=$AgentPrivateKey --set systemDefaultValues.spnOnboarding=false --kubeconfig $KubeConfig --kube-context $KubeContext + + $PSBoundParameters.Add('AgentPublicKeyCertificate', $AgentPublicKey) + Az.ConnectedKubernetes.internal\New-AzConnectedKubernetes @PSBoundParameters + } +} diff --git a/src/ConnectedKubernetes/custom/Remove-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/custom/Remove-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..0492a667023b --- /dev/null +++ b/src/ConnectedKubernetes/custom/Remove-AzConnectedKubernetes.ps1 @@ -0,0 +1,214 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Description +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/remove-azconnectedkubernetes +#> +function Remove-AzConnectedKubernetes { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(HelpMessage="Path to the kube config file")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Path to the kube config file + ${KubeConfig}, + + [Parameter(HelpMessage="Kubconfig context from current machine")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Kubconfig context from current machine + ${KubeContext}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + + process { + if ($PSBoundParameters.ContainsKey('KubeConfig')) { + $Null = $PSBoundParameters.Remove('KubeConfig') + } elseif (Test-Path Env:KUBECONFIG) { + $KubeConfig = Get-ChildItem -Path Env:KUBECONFIG + } elseif (Test-Path Env:Home) { + $KubeConfig = Join-Path -Path $Env:Home -ChildPath '.kube' | Join-Path -ChildPath 'config' + } else { + $KubeConfig = Join-Path -Path $Home -ChildPath '.kube' | Join-Path -ChildPath 'config' + } + if (-not (Test-Path $KubeConfig)) { + Write-Error 'Cannot find the kube-config. Please make sure that you have the kube-config on your machine.' + return + } + if ($PSBoundParameters.ContainsKey('KubeContext')) { + $Null = $PSBoundParameters.Remove('KubeContext') + } + if (($KubeContext -eq $null) -or ($KubeContext -eq '')) { + $KubeContext = kubectl config current-context + } + + #Region check helm install + try { + $HelmVersion = helm version --short --kubeconfig $KubeConfig + if ($HelmVersion.Contains("v2")) { + Write-Error "Helm version 3+ is required. Ensure that you have installed the latest version of Helm. Learn more at https://aka.ms/arc/k8s/onboarding-helm-install" + return + } + } catch { + Write-Error "Helm version 3+ is required. Ensure that you have installed the latest version of Helm. Learn more at https://aka.ms/arc/k8s/onboarding-helm-install" + throw + } + #Endregion + + #Region get release namespace + $ReleaseNamespace = $null + try { + $ReleaseNamespace = (helm status azure-arc -o json --kubeconfig $KubeConfig --kube-context $KubeContext | ConvertFrom-Json).namespace + } catch { + Write-Error "Fail to find the namespace for azure-arc." + } + #Endregion + + if ($null -eq $ReleaseNamespace) { + Az.ConnectedKubernetes.internal\Remove-AzConnectedKubernetes @PSBoundParameters + return + } + + $Configmap = kubectl get configmap --namespace azure-arc azure-clusterconfig -o json --kubeconfig $KubeConfig | ConvertFrom-Json + $ConfigmapRgName = $Configmap.data.AZURE_RESOURCE_GROUP + $ConfigmapClusterName = $Configmap.data.AZURE_RESOURCE_NAME + if ($PSBoundParameters.ContainsKey('InputObject')) { + $ResourceGroupName = $InputObject.ResourceGroupName + $ClusterName = $InputObject.ClusterName + $Null = $PSBoundParameters.Remove('InputObject') + $PSBoundParameters.Add('ResourceGroupName') + $PSBoundParameters.Add('ClusterName') + } + if (($ResourceGroupName -eq $ConfigmapRgName) -and ($ClusterName -eq $ConfigmapClusterName)) { + Az.ConnectedKubernetes.internal\Remove-AzConnectedKubernetes @PSBoundParameters + helm delete azure-arc --namespace $ReleaseNamespace --kubeconfig $KubeConfig --kube-context $KubeContext + } else { + Write-Error "The current context in the kubeconfig file does not correspond to the connected cluster resource specified. Agents installed on this cluster correspond to the resource group name '$ConfigmapRgName' and resource name '$ConfigmapClusterName'." + } + } +} diff --git a/src/ConnectedKubernetes/custom/Update-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/custom/Update-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..245140ee0c54 --- /dev/null +++ b/src/ConnectedKubernetes/custom/Update-AzConnectedKubernetes.ps1 @@ -0,0 +1,129 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to update certain properties of the connected cluster resource. +.Description +API to update certain properties of the connected cluster resource. + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/update-azconnectedkubernetes +#> +function Update-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + + process { + Az.ConnectedKubernetes.internal\Update-AzConnectedKubernetes @PSBoundParameters + } +} diff --git a/src/ConnectedKubernetes/custom/readme.md b/src/ConnectedKubernetes/custom/readme.md new file mode 100644 index 000000000000..275122977ca8 --- /dev/null +++ b/src/ConnectedKubernetes/custom/readme.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.ConnectedKubernetes` 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.ConnectedKubernetes.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.ConnectedKubernetes` 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.ConnectedKubernetes.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.ConnectedKubernetes.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundemental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.ConnectedKubernetes`. 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.ConnectedKubernetes.Models.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propegated to reference documentation via [help comments](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.ConnectedKubernetes`. +- `Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.ConnectedKubernetes`. For more information, see [readme.md](..\internal/readme.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.ProfileAttribute` + - Used in C# and script cmdlets to define which Azure profiles the cmdlet supports. This is only supported for Azure (`--azure`) modules. \ No newline at end of file diff --git a/src/ConnectedKubernetes/examples/Get-AzConnectedKubernetes.md b/src/ConnectedKubernetes/examples/Get-AzConnectedKubernetes.md new file mode 100644 index 000000000000..9958cc085709 --- /dev/null +++ b/src/ConnectedKubernetes/examples/Get-AzConnectedKubernetes.md @@ -0,0 +1,54 @@ +### Example 1: Get all connected kubernetes under a subscription +```powershell +PS C:\> Get-AzConnectedKubernetes + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +``` + +This command gets all connected kubernetes under a subscription. + +### Example 2: Get all connected kubernetes under the resource group +```powershell +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +``` + +This command gets all connected kubernetes under the resource group. + +### Example 3: Get a connected kubernetes +```powershell +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +``` + +This command gets a connected kubernetes. + +### Example 4: Get a connected kubernetes by object +```powershell +PS C:\> $conAks = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks +PS C:\> Get-AzConnectedKubernetes -InputObject $conAks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +``` + +This command gets a connected kubernetes by object. + + diff --git a/src/ConnectedKubernetes/examples/New-AzConnectedKubernetes.md b/src/ConnectedKubernetes/examples/New-AzConnectedKubernetes.md new file mode 100644 index 000000000000..cb14c07828da --- /dev/null +++ b/src/ConnectedKubernetes/examples/New-AzConnectedKubernetes.md @@ -0,0 +1,21 @@ +### Example 1: Create a connected kubernetes +```powershell +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t01 -ResourceGroupName connected-aks -Location +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +``` + +This command creates a connected kubernetes. + +### Example 1: Create a connected kubernetes with parameters kubeConfig and kubeContext +```powershell +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t02 -ResourceGroupName connected-aks -Location eastus -KubeConfig $HOME\.kube\config -KubeContext portal-aks-t01 + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t02 Microsoft.Kubernetes/connectedClusters +``` + +This command creates a connected kubernetes with parameters kubeConfig and kubeContext. + diff --git a/src/ConnectedKubernetes/examples/Remove-AzConnectedKubernetes.md b/src/ConnectedKubernetes/examples/Remove-AzConnectedKubernetes.md new file mode 100644 index 000000000000..6b13e1ad9a6d --- /dev/null +++ b/src/ConnectedKubernetes/examples/Remove-AzConnectedKubernetes.md @@ -0,0 +1,17 @@ +### Example 1: Remove a connected kubernetes +```powershell +PS C:\> Remove-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t01 + +``` + +This command removes a connected kubernetes + +### Example 2: Remove a connected kubernetes by object +```powershell +PS C:\> $connaks = Get-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -Name ps-connaks-t02 +PS C:\> Remove-AzConnectedKubernetes -InputObject $connaks + +``` + +This command removes a connected kubernetes by object + diff --git a/src/ConnectedKubernetes/examples/Update-AzConnectedKubernetes.md b/src/ConnectedKubernetes/examples/Update-AzConnectedKubernetes.md new file mode 100644 index 000000000000..5448843728de --- /dev/null +++ b/src/ConnectedKubernetes/examples/Update-AzConnectedKubernetes.md @@ -0,0 +1,23 @@ +### Example 1: Update a connected kubernetes +```powershell +PS C:\> Update-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t01 -Tag @{'key'='1'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +``` + +This command updates a connected kubernetes. + +### Example 2: Update a connected kubernetes by object +```powershell +PS C:\> $conn = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t03 +PS C:\> Update-AzConnectedKubernetes -InputObject $conn -Tag @{'key'='2'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t03 Microsoft.Kubernetes/connectedClusters +``` + +This command updates a connected kubernetes by object. + diff --git a/src/ConnectedKubernetes/export-surface.ps1 b/src/ConnectedKubernetes/export-surface.ps1 new file mode 100644 index 000000000000..b5e23206a75d --- /dev/null +++ b/src/ConnectedKubernetes/export-surface.ps1 @@ -0,0 +1,40 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.ConnectedKubernetes.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.ConnectedKubernetes' +$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/ConnectedKubernetes/exports/Get-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/exports/Get-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..dd98f93d57b7 --- /dev/null +++ b/src/ConnectedKubernetes/exports/Get-AzConnectedKubernetes.ps1 @@ -0,0 +1,195 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details. +.Description +Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details. +.Example +PS C:\> Get-AzConnectedKubernetes + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> $conAks = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks +PS C:\> Get-AzConnectedKubernetes -InputObject $conAks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/get-azconnectedkubernetes +#> +function Get-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='List1', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_Get'; + GetViaIdentity = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_GetViaIdentity'; + List = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_List'; + List1 = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/exports/New-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/exports/New-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..de664b436669 --- /dev/null +++ b/src/ConnectedKubernetes/exports/New-AzConnectedKubernetes.ps1 @@ -0,0 +1,165 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to register a new K8s cluster and thereby create a tracked resource in ARM +.Description +API to register a new K8s cluster and thereby create a tracked resource in ARM +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t01 -ResourceGroupName connected-aks -Location +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t02 -ResourceGroupName connected-aks -Location eastus -KubeConfig $HOME\.kube\config -KubeContext portal-aks-t01 + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t02 Microsoft.Kubernetes/connectedClusters + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/new-azconnectedkubernetes +#> +function New-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group to which the kubernetes cluster is registered. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the subscription to which the kubernetes cluster is registered. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Location of the cluster + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Path to the kube config file + ${KubeConfig}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Kubconfig context from current machine + ${KubeContext}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.ConnectedKubernetes.custom\New-AzConnectedKubernetes'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/exports/ProxyCmdletDefinitions.ps1 b/src/ConnectedKubernetes/exports/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..2ed83093b8d8 --- /dev/null +++ b/src/ConnectedKubernetes/exports/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,731 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details. +.Description +Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details. +.Example +PS C:\> Get-AzConnectedKubernetes + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> $conAks = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks +PS C:\> Get-AzConnectedKubernetes -InputObject $conAks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/get-azconnectedkubernetes +#> +function Get-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='List1', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_Get'; + GetViaIdentity = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_GetViaIdentity'; + List = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_List'; + List1 = 'Az.ConnectedKubernetes.private\Get-AzConnectedKubernetes_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to register a new K8s cluster and thereby create a tracked resource in ARM +.Description +API to register a new K8s cluster and thereby create a tracked resource in ARM +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t01 -ResourceGroupName connected-aks -Location +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t02 -ResourceGroupName connected-aks -Location eastus -KubeConfig $HOME\.kube\config -KubeContext portal-aks-t01 + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t02 Microsoft.Kubernetes/connectedClusters + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/new-azconnectedkubernetes +#> +function New-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group to which the kubernetes cluster is registered. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the subscription to which the kubernetes cluster is registered. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Location of the cluster + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Path to the kube config file + ${KubeConfig}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Kubconfig context from current machine + ${KubeContext}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.ConnectedKubernetes.custom\New-AzConnectedKubernetes'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Description +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Example +PS C:\> Remove-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t01 + +.Example +PS C:\> $connaks = Get-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -Name ps-connaks-t02 +PS C:\> Remove-AzConnectedKubernetes -InputObject $connaks + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/remove-azconnectedkubernetes +#> +function Remove-AzConnectedKubernetes { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Path to the kube config file + ${KubeConfig}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Kubconfig context from current machine + ${KubeContext}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.ConnectedKubernetes.custom\Remove-AzConnectedKubernetes'; + DeleteViaIdentity = 'Az.ConnectedKubernetes.custom\Remove-AzConnectedKubernetes'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to update certain properties of the connected cluster resource. +.Description +API to update certain properties of the connected cluster resource. +.Example +PS C:\> Update-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t01 -Tag @{'key'='1'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> $conn = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t03 +PS C:\> Update-AzConnectedKubernetes -InputObject $conn -Tag @{'key'='2'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t03 Microsoft.Kubernetes/connectedClusters + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/update-azconnectedkubernetes +#> +function Update-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.ConnectedKubernetes.custom\Update-AzConnectedKubernetes'; + UpdateViaIdentityExpanded = 'Az.ConnectedKubernetes.custom\Update-AzConnectedKubernetes'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/exports/Remove-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/exports/Remove-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..aa254ae2bc0e --- /dev/null +++ b/src/ConnectedKubernetes/exports/Remove-AzConnectedKubernetes.ps1 @@ -0,0 +1,194 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Description +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Example +PS C:\> Remove-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t01 + +.Example +PS C:\> $connaks = Get-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -Name ps-connaks-t02 +PS C:\> Remove-AzConnectedKubernetes -InputObject $connaks + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/remove-azconnectedkubernetes +#> +function Remove-AzConnectedKubernetes { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Path to the kube config file + ${KubeConfig}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Kubconfig context from current machine + ${KubeContext}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.ConnectedKubernetes.custom\Remove-AzConnectedKubernetes'; + DeleteViaIdentity = 'Az.ConnectedKubernetes.custom\Remove-AzConnectedKubernetes'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/exports/Update-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/exports/Update-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..be02864d928a --- /dev/null +++ b/src/ConnectedKubernetes/exports/Update-AzConnectedKubernetes.ps1 @@ -0,0 +1,177 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to update certain properties of the connected cluster resource. +.Description +API to update certain properties of the connected cluster resource. +.Example +PS C:\> Update-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t01 -Tag @{'key'='1'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> $conn = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t03 +PS C:\> Update-AzConnectedKubernetes -InputObject $conn -Tag @{'key'='2'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t03 Microsoft.Kubernetes/connectedClusters + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/update-azconnectedkubernetes +#> +function Update-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.ConnectedKubernetes.custom\Update-AzConnectedKubernetes'; + UpdateViaIdentityExpanded = 'Az.ConnectedKubernetes.custom\Update-AzConnectedKubernetes'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/exports/readme.md b/src/ConnectedKubernetes/exports/readme.md new file mode 100644 index 000000000000..bca11480886d --- /dev/null +++ b/src/ConnectedKubernetes/exports/readme.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.ConnectedKubernetes`. No other cmdlets in this repository are directly exported. What that means is the `Az.ConnectedKubernetes` module will run [Export-ModuleMember](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.ConnectedKubernetes.private.dll`) and from the `..\custom\Az.ConnectedKubernetes.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.ConnectedKubernetes.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/ConnectedKubernetes/generate-help.ps1 b/src/ConnectedKubernetes/generate-help.ps1 new file mode 100644 index 000000000000..f2b817e1640b --- /dev/null +++ b/src/ConnectedKubernetes/generate-help.ps1 @@ -0,0 +1,73 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.ConnectedKubernetes.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.ConnectedKubernetes.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/ConnectedKubernetes/generate-info.json b/src/ConnectedKubernetes/generate-info.json new file mode 100644 index 000000000000..2550f04b74e6 --- /dev/null +++ b/src/ConnectedKubernetes/generate-info.json @@ -0,0 +1,8 @@ +{ + "swagger_commit": "734319d8284f0bb20ba521808630be3e235ea344", + "autorest_core": "3.0.6282", + "autorest": "3.0.6187", + "node": "v10.16.0", + "autorest_remodeler": "2.1.27", + "autorest_powershell": "2.1.394" +} diff --git a/src/ConnectedKubernetes/generated/Module.cs b/src/ConnectedKubernetes/generated/Module.cs new file mode 100644 index 000000000000..c755404b17f3 --- /dev/null +++ b/src/ConnectedKubernetes/generated/Module.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline _pipelineWithProxy; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// Backing field for property. + private static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module _instance; + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module Instance => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module._instance?? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module._instance = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module()); + + /// The Name of this module + public string Name => @"Az.ConnectedKubernetes"; + + /// 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.ConnectedKubernetes"; + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_handler.UseProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + } + + /// Creates the module instance. + private Module() + { + /// constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + _webProxy.UseDefaultCredentials = proxyUseDefaultCredentials; + _handler.UseProxy = proxy != null; + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/ConnectedKubernetes.cs b/src/ConnectedKubernetes/generated/api/ConnectedKubernetes.cs new file mode 100644 index 000000000000..993e81651841 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/ConnectedKubernetes.cs @@ -0,0 +1,1542 @@ +// 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.ConnectedKubernetes +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// + /// Low-level API implementation for the ConnectedKubernetes service. + /// + public partial class ConnectedKubernetes + { + + /// + /// API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM). + /// + /// The ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// Parameters supplied to Create a Connected Cluster. + /// 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.ConnectedKubernetes.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 ConnectedClusterCreate(string subscriptionId, string resourceGroupName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + global::System.Uri.EscapeDataString(clusterName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM). + /// + /// + /// Parameters supplied to Create a Connected Cluster. + /// 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.ConnectedKubernetes.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 ConnectedClusterCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.Kubernetes/connectedClusters/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + clusterName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterCreate_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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: azure-async-operation + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_originalUri), Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedCluster.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// Parameters supplied to Create a Connected Cluster. + /// 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 ConnectedClusterCreate_Validate(string subscriptionId, string resourceGroupName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster body, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// + /// Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + /// + /// The ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterDelete(string subscriptionId, string resourceGroupName, string clusterName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + global::System.Uri.EscapeDataString(clusterName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// + /// Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + /// + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.Kubernetes/connectedClusters/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + clusterName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: location + var _finalUri = _response.GetFirstHeader(@"Location"); + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// 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 ConnectedClusterDelete_Validate(string subscriptionId, string resourceGroupName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + } + } + + /// + /// Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster + /// details. + /// + /// The ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// 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.ConnectedKubernetes.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 ConnectedClusterGet(string subscriptionId, string resourceGroupName, string clusterName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + global::System.Uri.EscapeDataString(clusterName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster + /// details. + /// + /// + /// 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.ConnectedKubernetes.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 ConnectedClusterGetViaIdentity(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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.Kubernetes/connectedClusters/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + clusterName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterGet_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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedCluster.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// 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 ConnectedClusterGet_Validate(string subscriptionId, string resourceGroupName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + } + } + + /// API to enumerate registered connected K8s clusters under a Resource Group + /// The ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// 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.ConnectedKubernetes.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 ConnectedClusterListByResourceGroup(string subscriptionId, string resourceGroupName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.Kubernetes/connectedClusters" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// API to enumerate registered connected K8s clusters under a Resource Group + /// + /// 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.ConnectedKubernetes.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 ConnectedClusterListByResourceGroupViaIdentity(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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.Kubernetes/connectedClusters$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.Kubernetes/connectedClusters" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterListByResourceGroup_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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// 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 ConnectedClusterListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + } + } + + /// API to enumerate registered connected K8s clusters under a Subscription + /// The ID of the target subscription. + /// 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.ConnectedKubernetes.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 ConnectedClusterListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.Kubernetes/connectedClusters" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// API to enumerate registered connected K8s clusters under a Subscription + /// + /// 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.ConnectedKubernetes.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 ConnectedClusterListBySubscriptionViaIdentity(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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.Kubernetes/connectedClusters$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.Kubernetes/connectedClusters'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.Kubernetes/connectedClusters" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterListBySubscription_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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ID of the target subscription. + /// 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 ConnectedClusterListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + } + } + + /// + /// Gets cluster user credentials of the connected cluster with a specified resource group and name. + /// + /// The ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// 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.ConnectedKubernetes.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 ConnectedClusterListClusterUserCredentials(string subscriptionId, string resourceGroupName, string clusterName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + global::System.Uri.EscapeDataString(clusterName) + + "/listClusterUserCredentials" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterListClusterUserCredentials_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Gets cluster user credentials of the connected cluster with a specified resource group and name. + /// + /// + /// 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.ConnectedKubernetes.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 ConnectedClusterListClusterUserCredentialsViaIdentity(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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.Kubernetes/connectedClusters/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}/listClusterUserCredentials'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + clusterName + + "/listClusterUserCredentials" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterListClusterUserCredentials_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterListClusterUserCredentials_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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.CredentialResults.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// 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 ConnectedClusterListClusterUserCredentials_Validate(string subscriptionId, string resourceGroupName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + } + } + + /// API to update certain properties of the connected cluster resource + /// The ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// Parameters supplied to update Connected Cluster. + /// 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.ConnectedKubernetes.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 ConnectedClusterUpdate(string subscriptionId, string resourceGroupName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + global::System.Uri.EscapeDataString(clusterName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// API to update certain properties of the connected cluster resource + /// + /// Parameters supplied to update Connected Cluster. + /// 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.ConnectedKubernetes.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 ConnectedClusterUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.Kubernetes/connectedClusters/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.Kubernetes/connectedClusters/" + + clusterName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ConnectedClusterUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ConnectedClusterUpdate_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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedCluster.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 ID of the target subscription. + /// The name of the resource group. The name is case insensitive. + /// The name of the Kubernetes cluster on which get is called. + /// Parameters supplied to update Connected Cluster. + /// 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 ConnectedClusterUpdate_Validate(string subscriptionId, string resourceGroupName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch body, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertMinimumLength(nameof(subscriptionId),subscriptionId,1); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Lists all of the available API operations for Connected Cluster resource. + /// 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.ConnectedKubernetes.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 OperationsGet(global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.Kubernetes/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists all of the available API operations for Connected Cluster resource. + /// + /// 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.ConnectedKubernetes.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 OperationsGetViaIdentity(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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-01-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.Kubernetes/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.Kubernetes/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.Kubernetes/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 OperationsGet_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.ConnectedKubernetes.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 OperationsGet_Validate(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.PowerShell.cs new file mode 100644 index 000000000000..3c595fecd119 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.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.ConnectedKubernetes.Models.Api10.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.ConnectedKubernetes.Models.Api10.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)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 Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.TypeConverter.cs new file mode 100644 index 000000000000..c2517f1a7bd7 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.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/ConnectedKubernetes/generated/api/Models/Api10/Resource.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.cs new file mode 100644 index 000000000000..94e327b6c0c6 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.cs @@ -0,0 +1,98 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResource, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal + { + + /// Backing field for property. + private string _id; + + /// + /// Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _type; + + /// + /// The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Fully qualified resource Id for the resource. Ex - /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.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the resource", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// + /// The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + internal partial interface IResourceInternal + + { + /// + /// Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + string Id { get; set; } + /// The name of the resource + string Name { get; set; } + /// + /// The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. + /// + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.json.cs new file mode 100644 index 000000000000..8a188d957f10 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/Resource.json.cs @@ -0,0 +1,113 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + 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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.PowerShell.cs new file mode 100644 index 000000000000..d4ed8b33f61e --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The resource model definition for a ARM tracked top level resource + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial class TrackedResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResource(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.ConnectedKubernetes.Models.Api10.ITrackedResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResource(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.ConnectedKubernetes.Models.Api10.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TrackedResource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)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 TrackedResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + } + /// The resource model definition for a ARM tracked top level resource + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial interface ITrackedResource + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.TypeConverter.cs new file mode 100644 index 000000000000..2e699099ce35 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResource.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/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.cs new file mode 100644 index 000000000000..4f0dd38f9b19 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.cs @@ -0,0 +1,107 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The resource model definition for a ARM tracked top level resource + public partial class TrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.Resource(); + + /// + /// Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTags()); set => this._tag = value; } + + /// + /// The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__resource).Type; } + + /// Creates an new instance. + public TrackedResource() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for a ARM tracked top level resource + public partial interface ITrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags Tag { get; set; } + + } + /// The resource model definition for a ARM tracked top level resource + internal partial interface ITrackedResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.json.cs new file mode 100644 index 000000000000..fd46ac66492e --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResource.json.cs @@ -0,0 +1,105 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The resource model definition for a ARM tracked top level resource + public partial class TrackedResource + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new TrackedResource(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.Resource(json); + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.PowerShell.cs new file mode 100644 index 000000000000..ff5a73da21e4 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial class TrackedResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResourceTags(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.ConnectedKubernetes.Models.Api10.ITrackedResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResourceTags(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.ConnectedKubernetes.Models.Api10.ITrackedResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TrackedResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial interface ITrackedResourceTags + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.TypeConverter.cs new file mode 100644 index 000000000000..7cf6f2df70b3 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResourceTags.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/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.cs new file mode 100644 index 000000000000..a6810236396d --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTagsInternal + { + + /// Creates an new instance. + public TrackedResourceTags() + { + + } + } + /// Resource tags. + public partial interface ITrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITrackedResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.dictionary.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.dictionary.cs new file mode 100644 index 000000000000..08e360613b56 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.json.cs new file mode 100644 index 000000000000..71aad39dd6ed --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api10/TrackedResourceTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new TrackedResourceTags(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + /// + internal TrackedResourceTags(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.PowerShell.cs new file mode 100644 index 000000000000..4ad152b5620b --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.PowerShell.cs @@ -0,0 +1,169 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// Represents a connected cluster. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterTypeConverter))] + public partial class ConnectedCluster + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedCluster(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterIdentityTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).KubernetesVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityTenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfile = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile) content.GetValueForProperty("AadProfile",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfile, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfileTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentPublicKeyCertificate, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentVersion = (string) content.GetValueForProperty("AgentVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityType = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityType, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).TotalNodeCount = (int?) content.GetValueForProperty("TotalNodeCount",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).TotalNodeCount, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileClientAppId = (string) content.GetValueForProperty("AadProfileClientAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileClientAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileServerAppId = (string) content.GetValueForProperty("AadProfileServerAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileServerAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileTenantId = (string) content.GetValueForProperty("AadProfileTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileTenantId, 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 ConnectedCluster(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterIdentityTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).KubernetesVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityTenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfile = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile) content.GetValueForProperty("AadProfile",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfile, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfileTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentPublicKeyCertificate, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentVersion = (string) content.GetValueForProperty("AgentVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AgentVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityType = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).IdentityType, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).TotalNodeCount = (int?) content.GetValueForProperty("TotalNodeCount",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).TotalNodeCount, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileClientAppId = (string) content.GetValueForProperty("AadProfileClientAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileClientAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileServerAppId = (string) content.GetValueForProperty("AadProfileServerAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileServerAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileTenantId = (string) content.GetValueForProperty("AadProfileTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal)this).AadProfileTenantId, 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.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedCluster(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedCluster(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Represents a connected cluster. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterTypeConverter))] + public partial interface IConnectedCluster + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.TypeConverter.cs new file mode 100644 index 000000000000..9b4952383071 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedCluster.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedCluster.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedCluster.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.cs new file mode 100644 index 000000000000..c21942370230 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.cs @@ -0,0 +1,305 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Represents a connected cluster. + public partial class ConnectedCluster : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResource(); + + /// The client app id configured on target K8 cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AadProfileClientAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfileClientAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfileClientAppId = value; } + + /// The server app id to access AD server + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AadProfileServerAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfileServerAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfileServerAppId = value; } + + /// The aad tenant id which is configured on target K8s cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AadProfileTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfileTenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfileTenantId = value; } + + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AgentPublicKeyCertificate { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AgentPublicKeyCertificate; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AgentPublicKeyCertificate = value; } + + /// Version of the agent running on the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AgentVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AgentVersion; } + + /// + /// Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity _identity; + + /// The identity of the connected cluster. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterIdentity()); set => this._identity = value; } + + /// + /// The principal id of connected cluster identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).PrincipalId; } + + /// + /// The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).TenantId; } + + /// + /// The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The + /// type 'None' means no identity is assigned to the connected cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).Type = value; } + + /// The Kubernetes version of the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string KubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).KubernetesVersion; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)__trackedResource).Location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Type = value; } + + /// Internal Acessors for AadProfile + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.AadProfile { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfile; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AadProfile = value; } + + /// Internal Acessors for AgentVersion + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.AgentVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AgentVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).AgentVersion = value; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).PrincipalId = value; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)Identity).TenantId = value; } + + /// Internal Acessors for KubernetesVersion + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.KubernetesVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).KubernetesVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).KubernetesVersion = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterProperties()); set { {_property = value;} } } + + /// Internal Acessors for TotalNodeCount + int? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterInternal.TotalNodeCount { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).TotalNodeCount; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).TotalNodeCount = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties _property; + + /// Describes the connected cluster resource properties. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterProperties()); set => this._property = value; } + + /// The current deployment state of connectedClusters. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).ProvisioningState = value; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal)__trackedResource).Tag = value; } + + /// Number of nodes present in the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public int? TotalNodeCount { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)Property).TotalNodeCount; } + + /// + /// The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public ConnectedCluster() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Represents a connected cluster. + public partial interface IConnectedCluster : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResource + { + /// The client app id configured on target K8 cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The client app id configured on target K8 cluster ", + SerializedName = @"clientAppId", + PossibleTypes = new [] { typeof(string) })] + string AadProfileClientAppId { get; set; } + /// The server app id to access AD server + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The server app id to access AD server", + SerializedName = @"serverAppId", + PossibleTypes = new [] { typeof(string) })] + string AadProfileServerAppId { get; set; } + /// The aad tenant id which is configured on target K8s cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The aad tenant id which is configured on target K8s cluster", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string AadProfileTenantId { get; set; } + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.", + SerializedName = @"agentPublicKeyCertificate", + PossibleTypes = new [] { typeof(string) })] + string AgentPublicKeyCertificate { get; set; } + /// Version of the agent running on the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Version of the agent running on the connected cluster resource", + SerializedName = @"agentVersion", + PossibleTypes = new [] { typeof(string) })] + string AgentVersion { get; } + /// + /// The principal id of connected cluster identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The principal id of connected cluster identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string IdentityPrincipalId { get; } + /// + /// The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string IdentityTenantId { get; } + /// + /// The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The + /// type 'None' means no identity is assigned to the connected cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The type 'None' means no identity is assigned to the connected cluster.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType IdentityType { get; set; } + /// The Kubernetes version of the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The Kubernetes version of the connected cluster resource", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string KubernetesVersion { get; } + /// The current deployment state of connectedClusters. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The current deployment state of connectedClusters.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState? ProvisioningState { get; set; } + /// Number of nodes present in the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Number of nodes present in the connected cluster resource", + SerializedName = @"totalNodeCount", + PossibleTypes = new [] { typeof(int) })] + int? TotalNodeCount { get; } + + } + /// Represents a connected cluster. + internal partial interface IConnectedClusterInternal : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceInternal + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile AadProfile { get; set; } + /// The client app id configured on target K8 cluster + string AadProfileClientAppId { get; set; } + /// The server app id to access AD server + string AadProfileServerAppId { get; set; } + /// The aad tenant id which is configured on target K8s cluster + string AadProfileTenantId { get; set; } + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + string AgentPublicKeyCertificate { get; set; } + /// Version of the agent running on the connected cluster resource + string AgentVersion { get; set; } + /// The identity of the connected cluster. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity Identity { get; set; } + /// + /// The principal id of connected cluster identity. This property will only be provided for a system assigned identity. + /// + string IdentityPrincipalId { get; set; } + /// + /// The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity. + /// + string IdentityTenantId { get; set; } + /// + /// The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The + /// type 'None' means no identity is assigned to the connected cluster. + /// + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType IdentityType { get; set; } + /// The Kubernetes version of the connected cluster resource + string KubernetesVersion { get; set; } + /// Describes the connected cluster resource properties. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties Property { get; set; } + /// The current deployment state of connectedClusters. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState? ProvisioningState { get; set; } + /// Number of nodes present in the connected cluster resource + int? TotalNodeCount { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.json.cs new file mode 100644 index 000000000000..b707232a7af1 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedCluster.json.cs @@ -0,0 +1,105 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Represents a connected cluster. + public partial class ConnectedCluster + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedCluster(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.TrackedResource(json); + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterIdentity.FromJson(__jsonIdentity) : Identity;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterProperties.FromJson(__jsonProperties) : Property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedCluster(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __trackedResource?.ToJson(container, serializationMode); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.PowerShell.cs new file mode 100644 index 000000000000..bba1c3d90330 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterAadProfileTypeConverter))] + public partial class ConnectedClusterAadProfile + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedClusterAadProfile(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ClientAppId = (string) content.GetValueForProperty("ClientAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ClientAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ServerAppId = (string) content.GetValueForProperty("ServerAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ServerAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).TenantId, 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 ConnectedClusterAadProfile(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ClientAppId = (string) content.GetValueForProperty("ClientAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ClientAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ServerAppId = (string) content.GetValueForProperty("ServerAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).ServerAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)this).TenantId, 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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedClusterAadProfile(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedClusterAadProfile(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterAadProfileTypeConverter))] + public partial interface IConnectedClusterAadProfile + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.TypeConverter.cs new file mode 100644 index 000000000000..c6bc3c24f8bf --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterAadProfileTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedClusterAadProfile.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedClusterAadProfile.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedClusterAadProfile.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.cs new file mode 100644 index 000000000000..e76e820c6585 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.cs @@ -0,0 +1,77 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedClusterAadProfile : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal + { + + /// Backing field for property. + private string _clientAppId; + + /// The client app id configured on target K8 cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string ClientAppId { get => this._clientAppId; set => this._clientAppId = value; } + + /// Backing field for property. + private string _serverAppId; + + /// The server app id to access AD server + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string ServerAppId { get => this._serverAppId; set => this._serverAppId = value; } + + /// Backing field for property. + private string _tenantId; + + /// The aad tenant id which is configured on target K8s cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; set => this._tenantId = value; } + + /// Creates an new instance. + public ConnectedClusterAadProfile() + { + + } + } + public partial interface IConnectedClusterAadProfile : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The client app id configured on target K8 cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The client app id configured on target K8 cluster ", + SerializedName = @"clientAppId", + PossibleTypes = new [] { typeof(string) })] + string ClientAppId { get; set; } + /// The server app id to access AD server + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The server app id to access AD server", + SerializedName = @"serverAppId", + PossibleTypes = new [] { typeof(string) })] + string ServerAppId { get; set; } + /// The aad tenant id which is configured on target K8s cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The aad tenant id which is configured on target K8s cluster", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + + } + internal partial interface IConnectedClusterAadProfileInternal + + { + /// The client app id configured on target K8 cluster + string ClientAppId { get; set; } + /// The server app id to access AD server + string ServerAppId { get; set; } + /// The aad tenant id which is configured on target K8s cluster + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.json.cs new file mode 100644 index 000000000000..b90956bbecd4 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterAadProfile.json.cs @@ -0,0 +1,104 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedClusterAadProfile + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedClusterAadProfile(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_clientAppId = If( json?.PropertyT("clientAppId"), out var __jsonClientAppId) ? (string)__jsonClientAppId : (string)ClientAppId;} + {_serverAppId = If( json?.PropertyT("serverAppId"), out var __jsonServerAppId) ? (string)__jsonServerAppId : (string)ServerAppId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)TenantId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedClusterAadProfile(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._clientAppId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._clientAppId.ToString()) : null, "clientAppId" ,container.Add ); + AddIf( null != (((object)this._serverAppId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._serverAppId.ToString()) : null, "serverAppId" ,container.Add ); + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.PowerShell.cs new file mode 100644 index 000000000000..72fd650926fe --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// Identity for the connected cluster. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterIdentityTypeConverter))] + public partial class ConnectedClusterIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedClusterIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).Type = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).Type, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).TenantId, 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 ConnectedClusterIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).Type = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).Type, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal)this).TenantId, 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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedClusterIdentity(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedClusterIdentity(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Identity for the connected cluster. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterIdentityTypeConverter))] + public partial interface IConnectedClusterIdentity + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.TypeConverter.cs new file mode 100644 index 000000000000..edcbca0c9c13 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedClusterIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedClusterIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedClusterIdentity.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.cs new file mode 100644 index 000000000000..2b8cee36bbfe --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.cs @@ -0,0 +1,107 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Identity for the connected cluster. + public partial class ConnectedClusterIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentityInternal.TenantId { get => this._tenantId; set { {_tenantId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// + /// The principal id of connected cluster identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Backing field for property. + private string _tenantId; + + /// + /// The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType _type; + + /// + /// The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The + /// type 'None' means no identity is assigned to the connected cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public ConnectedClusterIdentity() + { + + } + } + /// Identity for the connected cluster. + public partial interface IConnectedClusterIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// + /// The principal id of connected cluster identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The principal id of connected cluster identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// + /// The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + /// + /// The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The + /// type 'None' means no identity is assigned to the connected cluster. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The type 'None' means no identity is assigned to the connected cluster.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType Type { get; set; } + + } + /// Identity for the connected cluster. + internal partial interface IConnectedClusterIdentityInternal + + { + /// + /// The principal id of connected cluster identity. This property will only be provided for a system assigned identity. + /// + string PrincipalId { get; set; } + /// + /// The tenant id associated with the connected cluster. This property will only be provided for a system assigned identity. + /// + string TenantId { get; set; } + /// + /// The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The + /// type 'None' means no identity is assigned to the connected cluster. + /// + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.json.cs new file mode 100644 index 000000000000..9ff0c63a255c --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterIdentity.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Identity for the connected cluster. + public partial class ConnectedClusterIdentity + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedClusterIdentity(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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;} + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)PrincipalId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)TenantId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedClusterIdentity(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.PowerShell.cs new file mode 100644 index 000000000000..5fdaed3bf80a --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The paginated list of connected Clusters + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterListTypeConverter))] + public partial class ConnectedClusterList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedClusterList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConnectedClusterList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedClusterList(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedClusterList(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The paginated list of connected Clusters + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterListTypeConverter))] + public partial interface IConnectedClusterList + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.TypeConverter.cs new file mode 100644 index 000000000000..c3a09841265f --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedClusterList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedClusterList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedClusterList.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.cs new file mode 100644 index 000000000000..d5380dcf0f7b --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The paginated list of connected Clusters + public partial class ConnectedClusterList : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterListInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to fetch the next page of connected cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster[] _value; + + /// The list of connected clusters + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ConnectedClusterList() + { + + } + } + /// The paginated list of connected Clusters + public partial interface IConnectedClusterList : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The link to fetch the next page of connected cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The link to fetch the next page of connected cluster", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of connected clusters + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of connected clusters", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster[] Value { get; set; } + + } + /// The paginated list of connected Clusters + internal partial interface IConnectedClusterListInternal + + { + /// The link to fetch the next page of connected cluster + string NextLink { get; set; } + /// The list of connected clusters + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.json.cs new file mode 100644 index 000000000000..75d7b1922391 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterList.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The paginated list of connected Clusters + public partial class ConnectedClusterList + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedClusterList(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster) (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedCluster.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterList FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedClusterList(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.PowerShell.cs new file mode 100644 index 000000000000..62eca5bf63c7 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// Object containing updates for patch operations. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPatchTypeConverter))] + public partial class ConnectedClusterPatch + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedClusterPatch(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).AgentPublicKeyCertificate, 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 ConnectedClusterPatch(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal)this).AgentPublicKeyCertificate, 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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedClusterPatch(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedClusterPatch(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Object containing updates for patch operations. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPatchTypeConverter))] + public partial interface IConnectedClusterPatch + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.TypeConverter.cs new file mode 100644 index 000000000000..a8d2d105d558 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterPatchTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedClusterPatch.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedClusterPatch.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedClusterPatch.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.cs new file mode 100644 index 000000000000..e4c88f75bb9a --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.cs @@ -0,0 +1,82 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Object containing updates for patch operations. + public partial class ConnectedClusterPatch : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal + { + + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AgentPublicKeyCertificate { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchPropertiesInternal)Property).AgentPublicKeyCertificate; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchPropertiesInternal)Property).AgentPublicKeyCertificate = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchProperties()); set { {_property = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties _property; + + /// + /// Describes the connected cluster resource properties that can be updated during PATCH operation. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchProperties()); set => this._property = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchTags()); set => this._tag = value; } + + /// Creates an new instance. + public ConnectedClusterPatch() + { + + } + } + /// Object containing updates for patch operations. + public partial interface IConnectedClusterPatch : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.", + SerializedName = @"agentPublicKeyCertificate", + PossibleTypes = new [] { typeof(string) })] + string AgentPublicKeyCertificate { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags Tag { get; set; } + + } + /// Object containing updates for patch operations. + internal partial interface IConnectedClusterPatchInternal + + { + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + string AgentPublicKeyCertificate { get; set; } + /// + /// Describes the connected cluster resource properties that can be updated during PATCH operation. + /// + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties Property { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.json.cs new file mode 100644 index 000000000000..32aa034f70f7 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatch.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Object containing updates for patch operations. + public partial class ConnectedClusterPatch + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedClusterPatch(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchProperties.FromJson(__jsonProperties) : Property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedClusterPatch(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.PowerShell.cs new file mode 100644 index 000000000000..578f14699556 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.PowerShell.cs @@ -0,0 +1,131 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPatchPropertiesTypeConverter))] + public partial class ConnectedClusterPatchProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedClusterPatchProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchPropertiesInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchPropertiesInternal)this).AgentPublicKeyCertificate, 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 ConnectedClusterPatchProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchPropertiesInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchPropertiesInternal)this).AgentPublicKeyCertificate, 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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedClusterPatchProperties(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedClusterPatchProperties(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPatchPropertiesTypeConverter))] + public partial interface IConnectedClusterPatchProperties + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.TypeConverter.cs new file mode 100644 index 000000000000..1316a8d3d49b --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterPatchPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedClusterPatchProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedClusterPatchProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedClusterPatchProperties.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.cs new file mode 100644 index 000000000000..dfd1f840201d --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.cs @@ -0,0 +1,49 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedClusterPatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchPropertiesInternal + { + + /// Backing field for property. + private string _agentPublicKeyCertificate; + + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string AgentPublicKeyCertificate { get => this._agentPublicKeyCertificate; set => this._agentPublicKeyCertificate = value; } + + /// Creates an new instance. + public ConnectedClusterPatchProperties() + { + + } + } + public partial interface IConnectedClusterPatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.", + SerializedName = @"agentPublicKeyCertificate", + PossibleTypes = new [] { typeof(string) })] + string AgentPublicKeyCertificate { get; set; } + + } + internal partial interface IConnectedClusterPatchPropertiesInternal + + { + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + string AgentPublicKeyCertificate { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.json.cs new file mode 100644 index 000000000000..9833389c7649 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchProperties.json.cs @@ -0,0 +1,100 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedClusterPatchProperties + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedClusterPatchProperties(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_agentPublicKeyCertificate = If( json?.PropertyT("agentPublicKeyCertificate"), out var __jsonAgentPublicKeyCertificate) ? (string)__jsonAgentPublicKeyCertificate : (string)AgentPublicKeyCertificate;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedClusterPatchProperties(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._agentPublicKeyCertificate)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._agentPublicKeyCertificate.ToString()) : null, "agentPublicKeyCertificate" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.PowerShell.cs new file mode 100644 index 000000000000..3ffb3066a7a5 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPatchTagsTypeConverter))] + public partial class ConnectedClusterPatchTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedClusterPatchTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConnectedClusterPatchTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedClusterPatchTags(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedClusterPatchTags(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPatchTagsTypeConverter))] + public partial interface IConnectedClusterPatchTags + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.TypeConverter.cs new file mode 100644 index 000000000000..0ea40e82f2b3 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterPatchTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedClusterPatchTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedClusterPatchTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedClusterPatchTags.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.cs new file mode 100644 index 000000000000..1b7ea6eb8f22 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Resource tags. + public partial class ConnectedClusterPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTagsInternal + { + + /// Creates an new instance. + public ConnectedClusterPatchTags() + { + + } + } + /// Resource tags. + public partial interface IConnectedClusterPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface IConnectedClusterPatchTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.dictionary.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.dictionary.cs new file mode 100644 index 000000000000..76c7d202ac97 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedClusterPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatchTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.json.cs new file mode 100644 index 000000000000..5ec51cc42669 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterPatchTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Resource tags. + public partial class ConnectedClusterPatchTags + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ConnectedClusterPatchTags(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedClusterPatchTags(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.PowerShell.cs new file mode 100644 index 000000000000..e70de58b03b4 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.PowerShell.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPropertiesTypeConverter))] + public partial class ConnectedClusterProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedClusterProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfile = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile) content.GetValueForProperty("AadProfile",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfile, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfileTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentPublicKeyCertificate, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentVersion = (string) content.GetValueForProperty("AgentVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).KubernetesVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).TotalNodeCount = (int?) content.GetValueForProperty("TotalNodeCount",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).TotalNodeCount, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileClientAppId = (string) content.GetValueForProperty("AadProfileClientAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileClientAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileServerAppId = (string) content.GetValueForProperty("AadProfileServerAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileServerAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileTenantId = (string) content.GetValueForProperty("AadProfileTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileTenantId, 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 ConnectedClusterProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfile = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile) content.GetValueForProperty("AadProfile",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfile, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfileTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentPublicKeyCertificate = (string) content.GetValueForProperty("AgentPublicKeyCertificate",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentPublicKeyCertificate, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentVersion = (string) content.GetValueForProperty("AgentVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AgentVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).KubernetesVersion = (string) content.GetValueForProperty("KubernetesVersion",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).KubernetesVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).TotalNodeCount = (int?) content.GetValueForProperty("TotalNodeCount",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).TotalNodeCount, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileClientAppId = (string) content.GetValueForProperty("AadProfileClientAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileClientAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileServerAppId = (string) content.GetValueForProperty("AadProfileServerAppId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileServerAppId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileTenantId = (string) content.GetValueForProperty("AadProfileTenantId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal)this).AadProfileTenantId, 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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedClusterProperties(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedClusterProperties(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.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(ConnectedClusterPropertiesTypeConverter))] + public partial interface IConnectedClusterProperties + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.TypeConverter.cs new file mode 100644 index 000000000000..615486231841 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedClusterPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedClusterProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedClusterProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedClusterProperties.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.cs new file mode 100644 index 000000000000..643dea4fda92 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.cs @@ -0,0 +1,178 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedClusterProperties : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile _aadProfile; + + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile AadProfile { get => (this._aadProfile = this._aadProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfile()); set => this._aadProfile = value; } + + /// The client app id configured on target K8 cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AadProfileClientAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)AadProfile).ClientAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)AadProfile).ClientAppId = value; } + + /// The server app id to access AD server + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AadProfileServerAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)AadProfile).ServerAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)AadProfile).ServerAppId = value; } + + /// The aad tenant id which is configured on target K8s cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string AadProfileTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)AadProfile).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfileInternal)AadProfile).TenantId = value; } + + /// Backing field for property. + private string _agentPublicKeyCertificate; + + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string AgentPublicKeyCertificate { get => this._agentPublicKeyCertificate; set => this._agentPublicKeyCertificate = value; } + + /// Backing field for property. + private string _agentVersion; + + /// Version of the agent running on the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string AgentVersion { get => this._agentVersion; } + + /// Backing field for property. + private string _kubernetesVersion; + + /// The Kubernetes version of the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string KubernetesVersion { get => this._kubernetesVersion; } + + /// Internal Acessors for AadProfile + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal.AadProfile { get => (this._aadProfile = this._aadProfile ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfile()); set { {_aadProfile = value;} } } + + /// Internal Acessors for AgentVersion + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal.AgentVersion { get => this._agentVersion; set { {_agentVersion = value;} } } + + /// Internal Acessors for KubernetesVersion + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal.KubernetesVersion { get => this._kubernetesVersion; set { {_kubernetesVersion = value;} } } + + /// Internal Acessors for TotalNodeCount + int? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPropertiesInternal.TotalNodeCount { get => this._totalNodeCount; set { {_totalNodeCount = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState? _provisioningState; + + /// The current deployment state of connectedClusters. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState? ProvisioningState { get => this._provisioningState; set => this._provisioningState = value; } + + /// Backing field for property. + private int? _totalNodeCount; + + /// Number of nodes present in the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public int? TotalNodeCount { get => this._totalNodeCount; } + + /// Creates an new instance. + public ConnectedClusterProperties() + { + + } + } + public partial interface IConnectedClusterProperties : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The client app id configured on target K8 cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The client app id configured on target K8 cluster ", + SerializedName = @"clientAppId", + PossibleTypes = new [] { typeof(string) })] + string AadProfileClientAppId { get; set; } + /// The server app id to access AD server + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The server app id to access AD server", + SerializedName = @"serverAppId", + PossibleTypes = new [] { typeof(string) })] + string AadProfileServerAppId { get; set; } + /// The aad tenant id which is configured on target K8s cluster + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The aad tenant id which is configured on target K8s cluster", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string AadProfileTenantId { get; set; } + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.", + SerializedName = @"agentPublicKeyCertificate", + PossibleTypes = new [] { typeof(string) })] + string AgentPublicKeyCertificate { get; set; } + /// Version of the agent running on the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Version of the agent running on the connected cluster resource", + SerializedName = @"agentVersion", + PossibleTypes = new [] { typeof(string) })] + string AgentVersion { get; } + /// The Kubernetes version of the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The Kubernetes version of the connected cluster resource", + SerializedName = @"kubernetesVersion", + PossibleTypes = new [] { typeof(string) })] + string KubernetesVersion { get; } + /// The current deployment state of connectedClusters. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The current deployment state of connectedClusters.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState? ProvisioningState { get; set; } + /// Number of nodes present in the connected cluster resource + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Number of nodes present in the connected cluster resource", + SerializedName = @"totalNodeCount", + PossibleTypes = new [] { typeof(int) })] + int? TotalNodeCount { get; } + + } + internal partial interface IConnectedClusterPropertiesInternal + + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterAadProfile AadProfile { get; set; } + /// The client app id configured on target K8 cluster + string AadProfileClientAppId { get; set; } + /// The server app id to access AD server + string AadProfileServerAppId { get; set; } + /// The aad tenant id which is configured on target K8s cluster + string AadProfileTenantId { get; set; } + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + string AgentPublicKeyCertificate { get; set; } + /// Version of the agent running on the connected cluster resource + string AgentVersion { get; set; } + /// The Kubernetes version of the connected cluster resource + string KubernetesVersion { get; set; } + /// The current deployment state of connectedClusters. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState? ProvisioningState { get; set; } + /// Number of nodes present in the connected cluster resource + int? TotalNodeCount { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.json.cs new file mode 100644 index 000000000000..b0079cc0a516 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ConnectedClusterProperties.json.cs @@ -0,0 +1,119 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedClusterProperties + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedClusterProperties(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_aadProfile = If( json?.PropertyT("aadProfile"), out var __jsonAadProfile) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterAadProfile.FromJson(__jsonAadProfile) : AadProfile;} + {_agentPublicKeyCertificate = If( json?.PropertyT("agentPublicKeyCertificate"), out var __jsonAgentPublicKeyCertificate) ? (string)__jsonAgentPublicKeyCertificate : (string)AgentPublicKeyCertificate;} + {_agentVersion = If( json?.PropertyT("agentVersion"), out var __jsonAgentVersion) ? (string)__jsonAgentVersion : (string)AgentVersion;} + {_kubernetesVersion = If( json?.PropertyT("kubernetesVersion"), out var __jsonKubernetesVersion) ? (string)__jsonKubernetesVersion : (string)KubernetesVersion;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + {_totalNodeCount = If( json?.PropertyT("totalNodeCount"), out var __jsonTotalNodeCount) ? (int?)__jsonTotalNodeCount : TotalNodeCount;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedClusterProperties(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._aadProfile ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) this._aadProfile.ToJson(null,serializationMode) : null, "aadProfile" ,container.Add ); + AddIf( null != (((object)this._agentPublicKeyCertificate)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._agentPublicKeyCertificate.ToString()) : null, "agentPublicKeyCertificate" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._agentVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._agentVersion.ToString()) : null, "agentVersion" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._kubernetesVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._kubernetesVersion.ToString()) : null, "kubernetesVersion" ,container.Add ); + } + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._totalNodeCount ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNumber((int)this._totalNodeCount) : null, "totalNodeCount" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.PowerShell.cs new file mode 100644 index 000000000000..39a0d6a4efb5 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The credential result response. + [System.ComponentModel.TypeConverter(typeof(CredentialResultTypeConverter))] + public partial class CredentialResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CredentialResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Value = (byte[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Value, i => i); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CredentialResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Value = (byte[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal)this).Value, i => i); + 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.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CredentialResult(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.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CredentialResult(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.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The credential result response. + [System.ComponentModel.TypeConverter(typeof(CredentialResultTypeConverter))] + public partial interface ICredentialResult + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.TypeConverter.cs new file mode 100644 index 000000000000..f72d09a47fbe --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CredentialResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CredentialResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CredentialResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CredentialResult.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.cs new file mode 100644 index 000000000000..a4d6e4739194 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.cs @@ -0,0 +1,69 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The credential result response. + public partial class CredentialResult : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal + { + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Value + byte[] Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultInternal.Value { get => this._value; set { {_value = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the credential. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private byte[] _value; + + /// Base64-encoded Kubernetes configuration file. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public byte[] Value { get => this._value; } + + /// Creates an new instance. + public CredentialResult() + { + + } + } + /// The credential result response. + public partial interface ICredentialResult : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The name of the credential. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the credential.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Base64-encoded Kubernetes configuration file. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Base64-encoded Kubernetes configuration file.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(byte[]) })] + byte[] Value { get; } + + } + /// The credential result response. + internal partial interface ICredentialResultInternal + + { + /// The name of the credential. + string Name { get; set; } + /// Base64-encoded Kubernetes configuration file. + byte[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.json.cs new file mode 100644 index 000000000000..6ae44a836dbf --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResult.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The credential result response. + public partial class CredentialResult + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal CredentialResult(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_value = If( json?.PropertyT("value"), out var __w) ? System.Convert.FromBase64String( ((string)__w).Replace("_","/").Replace("-","+").PadRight( ((string)__w).Length + ((string)__w).Length * 3 % 4, '=') ) : null;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new CredentialResult(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._value ? global::System.Convert.ToBase64String( this._value) : null ,(v)=> container.Add( "value",v) ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.PowerShell.cs new file mode 100644 index 000000000000..5f64c9f9da00 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The list of credential result response. + [System.ComponentModel.TypeConverter(typeof(CredentialResultsTypeConverter))] + public partial class CredentialResults + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CredentialResults(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultsInternal)this).Kubeconfig = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult[]) content.GetValueForProperty("Kubeconfig",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultsInternal)this).Kubeconfig, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.CredentialResultTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CredentialResults(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultsInternal)this).Kubeconfig = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult[]) content.GetValueForProperty("Kubeconfig",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultsInternal)this).Kubeconfig, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.CredentialResultTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CredentialResults(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.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CredentialResults(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.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The list of credential result response. + [System.ComponentModel.TypeConverter(typeof(CredentialResultsTypeConverter))] + public partial interface ICredentialResults + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.TypeConverter.cs new file mode 100644 index 000000000000..28b8348267ef --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CredentialResultsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CredentialResults.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CredentialResults.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CredentialResults.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.cs new file mode 100644 index 000000000000..26b25adefec3 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.cs @@ -0,0 +1,49 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The list of credential result response. + public partial class CredentialResults : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultsInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult[] _kubeconfig; + + /// Base64-encoded Kubernetes configuration file. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult[] Kubeconfig { get => this._kubeconfig; } + + /// Internal Acessors for Kubeconfig + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult[] Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResultsInternal.Kubeconfig { get => this._kubeconfig; set { {_kubeconfig = value;} } } + + /// Creates an new instance. + public CredentialResults() + { + + } + } + /// The list of credential result response. + public partial interface ICredentialResults : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// Base64-encoded Kubernetes configuration file. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Base64-encoded Kubernetes configuration file.", + SerializedName = @"kubeconfigs", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult[] Kubeconfig { get; } + + } + /// The list of credential result response. + internal partial interface ICredentialResultsInternal + + { + /// Base64-encoded Kubernetes configuration file. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult[] Kubeconfig { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.json.cs new file mode 100644 index 000000000000..4fab27f08b03 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/CredentialResults.json.cs @@ -0,0 +1,112 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The list of credential result response. + public partial class CredentialResults + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal CredentialResults(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_kubeconfig = If( json?.PropertyT("kubeconfigs"), out var __jsonKubeconfigs) ? If( __jsonKubeconfigs as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResult) (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.CredentialResult.FromJson(__u) )) ))() : null : Kubeconfig;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ICredentialResults FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new CredentialResults(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + if (null != this._kubeconfig) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.XNodeArray(); + foreach( var __x in this._kubeconfig ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("kubeconfigs",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.PowerShell.cs new file mode 100644 index 000000000000..356b38f0d2ae --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The error response details containing error code and error message + [System.ComponentModel.TypeConverter(typeof(ErrorDetailsTypeConverter))] + public partial class ErrorDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDetails(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.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDetails(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Message, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)this).Message, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The error response details containing error code and error message + [System.ComponentModel.TypeConverter(typeof(ErrorDetailsTypeConverter))] + public partial interface IErrorDetails + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.TypeConverter.cs new file mode 100644 index 000000000000..a7811e31ad3f --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDetails.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.cs new file mode 100644 index 000000000000..9dc3f79c9db2 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.cs @@ -0,0 +1,69 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The error response details containing error code and error message + public partial class ErrorDetails : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal + { + + /// Backing field for property. + private string _code; + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private string _message; + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal.Message { get => this._message; set { {_message = value;} } } + + /// Creates an new instance. + public ErrorDetails() + { + + } + } + /// The error response details containing error code and error message + public partial interface IErrorDetails : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + + } + /// The error response details containing error code and error message + internal partial interface IErrorDetailsInternal + + { + /// The error code. + string Code { get; set; } + /// The error message. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.json.cs new file mode 100644 index 000000000000..1229ccc67fb2 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorDetails.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The error response details containing error code and error message + public partial class ErrorDetails + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetails(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_code = If( json?.PropertyT("code"), out var __jsonCode) ? (string)__jsonCode : (string)Code;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ErrorDetails(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.PowerShell.cs new file mode 100644 index 000000000000..9a144e92f461 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The error response that indicates why an operation has failed. + [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); + + /// + /// 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.ConnectedKubernetes.Models.Api202001Preview.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.ConnectedKubernetes.Models.Api202001Preview.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 + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorDetailsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorDetailsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The error response that indicates why an operation has failed. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.TypeConverter.cs new file mode 100644 index 000000000000..43596acd295a --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.cs new file mode 100644 index 000000000000..780f7eddede7 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.cs @@ -0,0 +1,75 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The error response that indicates why an operation has failed. + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal + { + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)Error).Code; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails _error; + + /// The error response details containing error code and error message + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorDetails()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)Error).Message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)Error).Code = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ErrorDetails()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetailsInternal)Error).Message = value; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// The error response that indicates why an operation has failed. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + + } + /// The error response that indicates why an operation has failed. + internal partial interface IErrorResponseInternal + + { + /// The error code. + string Code { get; set; } + /// The error response details containing error code and error message + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorDetails Error { get; set; } + /// The error message. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.json.cs new file mode 100644 index 000000000000..389b94163065 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/ErrorResponse.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The error response that indicates why an operation has failed. + 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Models.Api202001Preview.ErrorDetails.FromJson(__jsonError) : Error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.PowerShell.cs new file mode 100644 index 000000000000..618ce5bbed61 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.PowerShell.cs @@ -0,0 +1,141 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The Connected cluster API operation + [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); + + /// + /// 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.ConnectedKubernetes.Models.Api202001Preview.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.ConnectedKubernetes.Models.Api202001Preview.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.ConnectedKubernetes.Models.Api202001Preview.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The Connected cluster API operation + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.TypeConverter.cs new file mode 100644 index 000000000000..ca6900d4a649 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.cs new file mode 100644 index 000000000000..6b703a5c1431 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.cs @@ -0,0 +1,117 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The Connected cluster API operation + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay _display; + + /// The object that represents the operation. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationDisplay()); } + + /// Description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Description = value; } + + /// Operation type: Read, write, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Operation = value; } + + /// Service provider: Microsoft.connectedClusters + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Provider = value; } + + /// Connected Cluster Resource on which the operation is performed + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Backing field for property. + private string _name; + + /// Operation name: {Microsoft.Kubernetes}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// The Connected cluster API operation + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// Description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description of the operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; set; } + /// Operation type: Read, write, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Operation type: Read, write, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; set; } + /// Service provider: Microsoft.connectedClusters + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Service provider: Microsoft.connectedClusters", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; set; } + /// Connected Cluster Resource on which the operation is performed + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Connected Cluster Resource on which the operation is performed", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; set; } + /// Operation name: {Microsoft.Kubernetes}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Operation name: {Microsoft.Kubernetes}/{resource}/{operation}", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + + } + /// The Connected cluster API operation + internal partial interface IOperationInternal + + { + /// The object that represents the operation. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay Display { get; set; } + /// Description of the operation. + string DisplayDescription { get; set; } + /// Operation type: Read, write, delete, etc. + string DisplayOperation { get; set; } + /// Service provider: Microsoft.connectedClusters + string DisplayProvider { get; set; } + /// Connected Cluster Resource on which the operation is performed + string DisplayResource { get; set; } + /// Operation name: {Microsoft.Kubernetes}/{resource}/{operation} + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.json.cs new file mode 100644 index 000000000000..039bcc605bf3 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/Operation.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The Connected cluster API operation + 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Models.Api202001Preview.OperationDisplay.FromJson(__jsonDisplay) : Display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.PowerShell.cs new file mode 100644 index 000000000000..51a65879601b --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The object that represents the 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); + + /// + /// 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.ConnectedKubernetes.Models.Api202001Preview.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.ConnectedKubernetes.Models.Api202001Preview.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.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The object that represents the operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.TypeConverter.cs new file mode 100644 index 000000000000..a9923ddc491f --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.cs new file mode 100644 index 000000000000..659d7f86bd32 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.cs @@ -0,0 +1,97 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The object that represents the operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// Description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _operation; + + /// Operation type: Read, write, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Operation { get => this._operation; set => this._operation = value; } + + /// Backing field for property. + private string _provider; + + /// Service provider: Microsoft.connectedClusters + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Provider { get => this._provider; set => this._provider = value; } + + /// Backing field for property. + private string _resource; + + /// Connected Cluster Resource on which the operation is performed + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Resource { get => this._resource; set => this._resource = value; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// The object that represents the operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// Description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description of the operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// Operation type: Read, write, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Operation type: Read, write, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; set; } + /// Service provider: Microsoft.connectedClusters + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Service provider: Microsoft.connectedClusters", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; set; } + /// Connected Cluster Resource on which the operation is performed + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Connected Cluster Resource on which the operation is performed", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; set; } + + } + /// The object that represents the operation. + internal partial interface IOperationDisplayInternal + + { + /// Description of the operation. + string Description { get; set; } + /// Operation type: Read, write, delete, etc. + string Operation { get; set; } + /// Service provider: Microsoft.connectedClusters + string Provider { get; set; } + /// Connected Cluster Resource on which the operation is performed + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.json.cs new file mode 100644 index 000000000000..6e9610cca541 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationDisplay.json.cs @@ -0,0 +1,107 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The object that represents the 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)Description;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)Operation;} + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)Provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)Resource;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.PowerShell.cs new file mode 100644 index 000000000000..31cdcec40876 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// The paginated list of connected cluster API operations. + [System.ComponentModel.TypeConverter(typeof(OperationListTypeConverter))] + public partial class OperationList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationList(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.ConnectedKubernetes.Models.Api202001Preview.IOperationList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationList(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.ConnectedKubernetes.Models.Api202001Preview.IOperationList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.OperationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The paginated list of connected cluster API operations. + [System.ComponentModel.TypeConverter(typeof(OperationListTypeConverter))] + public partial interface IOperationList + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.TypeConverter.cs new file mode 100644 index 000000000000..3f73b663d0e9 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationList.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/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.cs new file mode 100644 index 000000000000..2a70d17cb039 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.cs @@ -0,0 +1,66 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The paginated list of connected cluster API operations. + public partial class OperationList : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationList, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal + { + + /// Internal Acessors for Value + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation[] Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationListInternal.Value { get => this._value; set { {_value = value;} } } + + /// Backing field for property. + private string _nextLink; + + /// The link to fetch the next page of connected cluster API operations. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation[] _value; + + /// The list of connected cluster API operations. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation[] Value { get => this._value; } + + /// Creates an new instance. + public OperationList() + { + + } + } + /// The paginated list of connected cluster API operations. + public partial interface IOperationList : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The link to fetch the next page of connected cluster API operations. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The link to fetch the next page of connected cluster API operations.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of connected cluster API operations. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The list of connected cluster API operations.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation) })] + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation[] Value { get; } + + } + /// The paginated list of connected cluster API operations. + internal partial interface IOperationListInternal + + { + /// The link to fetch the next page of connected cluster API operations. + string NextLink { get; set; } + /// The list of connected cluster API operations. + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.json.cs b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.json.cs new file mode 100644 index 000000000000..978774c2fd7e --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/Api202001Preview/OperationList.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// The paginated list of connected cluster API operations. + public partial class OperationList + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperationList FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new OperationList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal OperationList(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.Operation.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode.IncludeReadOnly)) + { + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.PowerShell.cs b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.PowerShell.cs new file mode 100644 index 000000000000..38c65da0e865 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.PowerShell.cs @@ -0,0 +1,142 @@ +// 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.ConnectedKubernetes.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ConnectedKubernetesIdentityTypeConverter))] + public partial class ConnectedKubernetesIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ConnectedKubernetesIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ClusterName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ConnectedKubernetesIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ClusterName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ConnectedKubernetesIdentity(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.ConnectedKubernetes.Models.IConnectedKubernetesIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ConnectedKubernetesIdentity(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.ConnectedKubernetes.Models.IConnectedKubernetesIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(ConnectedKubernetesIdentityTypeConverter))] + public partial interface IConnectedKubernetesIdentity + + { + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.TypeConverter.cs new file mode 100644 index 000000000000..e3efe8f9bdce --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.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.ConnectedKubernetes.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ConnectedKubernetesIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity 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 ConnectedKubernetesIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ConnectedKubernetesIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ConnectedKubernetesIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ConnectedKubernetesIdentity.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/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.cs b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.cs new file mode 100644 index 000000000000..5eeab3a9b73b --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedKubernetesIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentityInternal + { + + /// Backing field for property. + private string _clusterName; + + /// The name of the Kubernetes cluster on which get is called. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Origin(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public ConnectedKubernetesIdentity() + { + + } + } + public partial interface IConnectedKubernetesIdentity : + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IJsonSerializable + { + /// The name of the Kubernetes cluster on which get is called. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the Kubernetes cluster on which get is called.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + string ClusterName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the resource group. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroupName { get; set; } + /// The ID of the target subscription. + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface IConnectedKubernetesIdentityInternal + + { + /// The name of the Kubernetes cluster on which get is called. + string ClusterName { get; set; } + /// Resource identity path + string Id { get; set; } + /// The name of the resource group. The name is case insensitive. + string ResourceGroupName { get; set; } + /// The ID of the target subscription. + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.json.cs b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.json.cs new file mode 100644 index 000000000000..62d8253df4c9 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Models/ConnectedKubernetesIdentity.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.ConnectedKubernetes.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + public partial class ConnectedKubernetesIdentity + { + + /// + /// 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.ConnectedKubernetes.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject instance to deserialize from. + internal ConnectedKubernetesIdentity(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_clusterName = If( json?.PropertyT("clusterName"), out var __jsonClusterName) ? (string)__jsonClusterName : (string)ClusterName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)ResourceGroupName;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)SubscriptionId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject json ? new ConnectedKubernetesIdentity(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.ConnectedKubernetes.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._clusterName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._clusterName.ToString()) : null, "clusterName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.Completer.cs b/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.Completer.cs new file mode 100644 index 000000000000..02ac0481d157 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.Completer.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support +{ + + /// Argument completer implementation for ProvisioningState. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningStateTypeConverter))] + public partial struct ProvisioningState : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Succeeded".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Succeeded", "Succeeded", global::System.Management.Automation.CompletionResultType.ParameterValue, "Succeeded"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Failed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Failed", "Failed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Failed"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Canceled".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Canceled", "Canceled", global::System.Management.Automation.CompletionResultType.ParameterValue, "Canceled"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Provisioning".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Provisioning", "Provisioning", global::System.Management.Automation.CompletionResultType.ParameterValue, "Provisioning"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Updating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Updating", "Updating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Updating"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Deleting".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Deleting", "Deleting", global::System.Management.Automation.CompletionResultType.ParameterValue, "Deleting"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Accepted".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Accepted", "Accepted", global::System.Management.Automation.CompletionResultType.ParameterValue, "Accepted"); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.TypeConverter.cs new file mode 100644 index 000000000000..ac734a27fba6 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support +{ + + /// TypeConverter implementation for ProvisioningState. + public partial class ProvisioningStateTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ProvisioningState.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.cs b/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.cs new file mode 100644 index 000000000000..ec5f157ce9c9 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Support/ProvisioningState.cs @@ -0,0 +1,107 @@ +// 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.ConnectedKubernetes.Support +{ + + public partial struct ProvisioningState : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState Accepted = @"Accepted"; + + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState Canceled = @"Canceled"; + + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState Deleting = @"Deleting"; + + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState Failed = @"Failed"; + + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState Provisioning = @"Provisioning"; + + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState Succeeded = @"Succeeded"; + + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState Updating = @"Updating"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to ProvisioningState + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ProvisioningState(System.Convert.ToString(value)); + } + + /// Compares values of enum type ProvisioningState + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ProvisioningState (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ProvisioningState && Equals((ProvisioningState)obj); + } + + /// Returns hashCode for enum ProvisioningState + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private ProvisioningState(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for ProvisioningState + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ProvisioningState + /// the value to convert to an instance of . + + public static implicit operator ProvisioningState(string value) + { + return new ProvisioningState(value); + } + + /// Implicit operator to convert ProvisioningState to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState e) + { + return e._value; + } + + /// Overriding != operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.Completer.cs b/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.Completer.cs new file mode 100644 index 000000000000..d683e2b3b076 --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.Completer.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. +// 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.ConnectedKubernetes.Support +{ + + /// Argument completer implementation for ResourceIdentityType. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityTypeTypeConverter))] + public partial struct ResourceIdentityType : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "None".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("None", "None", global::System.Management.Automation.CompletionResultType.ParameterValue, "None"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "SystemAssigned".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("SystemAssigned", "SystemAssigned", global::System.Management.Automation.CompletionResultType.ParameterValue, "SystemAssigned"); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.TypeConverter.cs b/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.TypeConverter.cs new file mode 100644 index 000000000000..9baa9e2b4abc --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support +{ + + /// TypeConverter implementation for ResourceIdentityType. + public partial class ResourceIdentityTypeTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ResourceIdentityType.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.cs b/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.cs new file mode 100644 index 000000000000..bdfac78b82ce --- /dev/null +++ b/src/ConnectedKubernetes/generated/api/Support/ResourceIdentityType.cs @@ -0,0 +1,97 @@ +// 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.ConnectedKubernetes.Support +{ + + public partial struct ResourceIdentityType : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType None = @"None"; + + public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType SystemAssigned = @"SystemAssigned"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to ResourceIdentityType + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ResourceIdentityType(System.Convert.ToString(value)); + } + + /// Compares values of enum type ResourceIdentityType + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ResourceIdentityType (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ResourceIdentityType && Equals((ResourceIdentityType)obj); + } + + /// Returns hashCode for enum ResourceIdentityType + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private ResourceIdentityType(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for ResourceIdentityType + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ResourceIdentityType + /// the value to convert to an instance of . + + public static implicit operator ResourceIdentityType(string value) + { + return new ResourceIdentityType(value); + } + + /// Implicit operator to convert ResourceIdentityType to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType e) + { + return e._value; + } + + /// Overriding != operator for enum ResourceIdentityType + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType e1, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ResourceIdentityType + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType e1, Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_Get.cs b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_Get.cs new file mode 100644 index 000000000000..6635bb626e09 --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_Get.cs @@ -0,0 +1,402 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// + /// Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster + /// details. + /// + /// + /// [OpenAPI] ConnectedCluster_Get=>GET:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzConnectedKubernetes_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class GetAzConnectedKubernetes_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the Kubernetes cluster on which get is called. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Kubernetes cluster on which get is called.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Kubernetes cluster on which get is called.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("Name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The ID of the target subscription. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzConnectedKubernetes_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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterGet(SubscriptionId, ResourceGroupName, ClusterName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterName=ClusterName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_GetViaIdentity.cs b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_GetViaIdentity.cs new file mode 100644 index 000000000000..6ee992e3620d --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_GetViaIdentity.cs @@ -0,0 +1,380 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// + /// Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster + /// details. + /// + /// + /// [OpenAPI] ConnectedCluster_Get=>GET:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzConnectedKubernetes_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class GetAzConnectedKubernetes_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzConnectedKubernetes_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConnectedClusterGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConnectedClusterGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ClusterName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_List.cs b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_List.cs new file mode 100644 index 000000000000..d869636cb7c2 --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_List.cs @@ -0,0 +1,395 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// API to enumerate registered connected K8s clusters under a Resource Group + /// + /// [OpenAPI] ConnectedCluster_ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzConnectedKubernetes_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"API to enumerate registered connected K8s clusters under a Resource Group")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class GetAzConnectedKubernetes_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The ID of the target subscription. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzConnectedKubernetes_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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_List1.cs b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_List1.cs new file mode 100644 index 000000000000..4bcc2a28f2aa --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/GetAzConnectedKubernetes_List1.cs @@ -0,0 +1,381 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// API to enumerate registered connected K8s clusters under a Subscription + /// + /// [OpenAPI] ConnectedCluster_ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.Kubernetes/connectedClusters" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzConnectedKubernetes_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"API to enumerate registered connected K8s clusters under a Subscription")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class GetAzConnectedKubernetes_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The ID of the target subscription. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzConnectedKubernetes_List1() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/GetAzOperation_Get.cs b/src/ConnectedKubernetes/generated/cmdlets/GetAzOperation_Get.cs new file mode 100644 index 000000000000..3f22deddce19 --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/GetAzOperation_Get.cs @@ -0,0 +1,361 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// Lists all of the available API operations for Connected Cluster resource. + /// + /// [OpenAPI] Operations_Get=>GET:"/providers/Microsoft.Kubernetes/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzOperation_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"Lists all of the available API operations for Connected Cluster resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class GetAzOperation_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzOperation_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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsGet(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsGet_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/NewAzConnectedKubernetes_CreateExpanded.cs b/src/ConnectedKubernetes/generated/cmdlets/NewAzConnectedKubernetes_CreateExpanded.cs new file mode 100644 index 000000000000..5027d0ff3694 --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/NewAzConnectedKubernetes_CreateExpanded.cs @@ -0,0 +1,571 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// + /// API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM). + /// + /// + /// [OpenAPI] ConnectedCluster_Create=>PUT:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzConnectedKubernetes_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM).")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class NewAzConnectedKubernetes_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// The client app id configured on target K8 cluster + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The client app id configured on target K8 cluster ")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The client app id configured on target K8 cluster ", + SerializedName = @"clientAppId", + PossibleTypes = new [] { typeof(string) })] + public string AadProfileClientAppId { get => ConnectedClusterBody.AadProfileClientAppId ?? null; set => ConnectedClusterBody.AadProfileClientAppId = value; } + + /// The server app id to access AD server + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The server app id to access AD server")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The server app id to access AD server", + SerializedName = @"serverAppId", + PossibleTypes = new [] { typeof(string) })] + public string AadProfileServerAppId { get => ConnectedClusterBody.AadProfileServerAppId ?? null; set => ConnectedClusterBody.AadProfileServerAppId = value; } + + /// The aad tenant id which is configured on target K8s cluster + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The aad tenant id which is configured on target K8s cluster")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The aad tenant id which is configured on target K8s cluster", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + public string AadProfileTenantId { get => ConnectedClusterBody.AadProfileTenantId ?? null; set => ConnectedClusterBody.AadProfileTenantId = value; } + + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.", + SerializedName = @"agentPublicKeyCertificate", + PossibleTypes = new [] { typeof(string) })] + public string AgentPublicKeyCertificate { get => ConnectedClusterBody.AgentPublicKeyCertificate ?? null; set => ConnectedClusterBody.AgentPublicKeyCertificate = value; } + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the Kubernetes cluster on which get is called. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Kubernetes cluster on which get is called.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Kubernetes cluster on which get is called.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("Name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster _connectedClusterBody= new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedCluster(); + + /// Represents a connected cluster. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster ConnectedClusterBody { get => this._connectedClusterBody; set => this._connectedClusterBody = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// + /// The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The + /// type 'None' means no identity is assigned to the connected cluster. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The type 'None' means no identity is assigned to the connected cluster.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The type of identity used for the connected cluster. The type 'SystemAssigned, includes a system created identity. The type 'None' means no identity is assigned to the connected cluster.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType) })] + [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType))] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType IdentityType { get => ConnectedClusterBody.IdentityType; set => ConnectedClusterBody.IdentityType = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The geo-location where the resource lives + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ConnectedClusterBody.Location ?? null; set => ConnectedClusterBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.HttpPipeline Pipeline { get; set; } + + /// The current deployment state of connectedClusters. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The current deployment state of connectedClusters.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The current deployment state of connectedClusters.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState) })] + [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState))] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState ProvisioningState { get => ConnectedClusterBody.ProvisioningState ?? ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState)""); set => ConnectedClusterBody.ProvisioningState = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags Tag { get => ConnectedClusterBody.Tag ?? null /* object */; set => ConnectedClusterBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzConnectedKubernetes_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Cmdlets.NewAzConnectedKubernetes_CreateExpanded Clone() + { + var clone = new NewAzConnectedKubernetes_CreateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ConnectedClusterBody = this.ConnectedClusterBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.ClusterName = this.ClusterName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzConnectedKubernetes_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConnectedClusterCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterCreate(SubscriptionId, ResourceGroupName, ClusterName, ConnectedClusterBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterName=ClusterName,body=ConnectedClusterBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName, body=ConnectedClusterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName, body=ConnectedClusterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/RemoveAzConnectedKubernetes_Delete.cs b/src/ConnectedKubernetes/generated/cmdlets/RemoveAzConnectedKubernetes_Delete.cs new file mode 100644 index 000000000000..254c2a09cc0b --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/RemoveAzConnectedKubernetes_Delete.cs @@ -0,0 +1,507 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// + /// Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + /// + /// + /// [OpenAPI] ConnectedCluster_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzConnectedKubernetes_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM).")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class RemoveAzConnectedKubernetes_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the Kubernetes cluster on which get is called. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Kubernetes cluster on which get is called.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Kubernetes cluster on which get is called.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("Name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzConnectedKubernetes_Delete + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Cmdlets.RemoveAzConnectedKubernetes_Delete Clone() + { + var clone = new RemoveAzConnectedKubernetes_Delete(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.ClusterName = this.ClusterName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConnectedClusterDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterDelete(SubscriptionId, ResourceGroupName, ClusterName, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterName=ClusterName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzConnectedKubernetes_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/RemoveAzConnectedKubernetes_DeleteViaIdentity.cs b/src/ConnectedKubernetes/generated/cmdlets/RemoveAzConnectedKubernetes_DeleteViaIdentity.cs new file mode 100644 index 000000000000..2ebac95186f1 --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/RemoveAzConnectedKubernetes_DeleteViaIdentity.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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// + /// Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + /// + /// + /// [OpenAPI] ConnectedCluster_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzConnectedKubernetes_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM).")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class RemoveAzConnectedKubernetes_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzConnectedKubernetes_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Cmdlets.RemoveAzConnectedKubernetes_DeleteViaIdentity Clone() + { + var clone = new RemoveAzConnectedKubernetes_DeleteViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConnectedClusterDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConnectedClusterDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConnectedClusterDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ClusterName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzConnectedKubernetes_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/UpdateAzConnectedKubernetes_UpdateExpanded.cs b/src/ConnectedKubernetes/generated/cmdlets/UpdateAzConnectedKubernetes_UpdateExpanded.cs new file mode 100644 index 000000000000..9c4b7a26cd32 --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/UpdateAzConnectedKubernetes_UpdateExpanded.cs @@ -0,0 +1,431 @@ +// 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.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// API to update certain properties of the connected cluster resource + /// + /// [OpenAPI] ConnectedCluster_Update=>PATCH:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzConnectedKubernetes_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"API to update certain properties of the connected cluster resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class UpdateAzConnectedKubernetes_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.", + SerializedName = @"agentPublicKeyCertificate", + PossibleTypes = new [] { typeof(string) })] + public string AgentPublicKeyCertificate { get => ConnectedClusterPatchBody.AgentPublicKeyCertificate ?? null; set => ConnectedClusterPatchBody.AgentPublicKeyCertificate = value; } + + /// 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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the Kubernetes cluster on which get is called. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Kubernetes cluster on which get is called.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Kubernetes cluster on which get is called.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("Name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch _connectedClusterPatchBody= new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatch(); + + /// Object containing updates for patch operations. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch ConnectedClusterPatchBody { get => this._connectedClusterPatchBody; set => this._connectedClusterPatchBody = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags Tag { get => ConnectedClusterPatchBody.Tag ?? null /* object */; set => ConnectedClusterPatchBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConnectedClusterUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ConnectedClusterUpdate(SubscriptionId, ResourceGroupName, ClusterName, ConnectedClusterPatchBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterName=ClusterName,body=ConnectedClusterPatchBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzConnectedKubernetes_UpdateExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName, body=ConnectedClusterPatchBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterName=ClusterName, body=ConnectedClusterPatchBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/cmdlets/UpdateAzConnectedKubernetes_UpdateViaIdentityExpanded.cs b/src/ConnectedKubernetes/generated/cmdlets/UpdateAzConnectedKubernetes_UpdateViaIdentityExpanded.cs new file mode 100644 index 000000000000..60ec9488f34e --- /dev/null +++ b/src/ConnectedKubernetes/generated/cmdlets/UpdateAzConnectedKubernetes_UpdateViaIdentityExpanded.cs @@ -0,0 +1,412 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Extensions; + + /// API to update certain properties of the connected cluster resource + /// + /// [OpenAPI] ConnectedCluster_Update=>PATCH:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Kubernetes/connectedClusters/{clusterName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzConnectedKubernetes_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster))] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Description(@"API to update certain properties of the connected cluster resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Generated] + public partial class UpdateAzConnectedKubernetes_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// + /// Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure.", + SerializedName = @"agentPublicKeyCertificate", + PossibleTypes = new [] { typeof(string) })] + public string AgentPublicKeyCertificate { get => ConnectedClusterPatchBody.AgentPublicKeyCertificate ?? null; set => ConnectedClusterPatchBody.AgentPublicKeyCertificate = value; } + + /// 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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ConnectedKubernetes Client => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch _connectedClusterPatchBody= new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.ConnectedClusterPatch(); + + /// Object containing updates for patch operations. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatch ConnectedClusterPatchBody { get => this._connectedClusterPatchBody; set => this._connectedClusterPatchBody = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags Tag { get => ConnectedClusterPatchBody.Tag ?? null /* object */; set => ConnectedClusterPatchBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ConnectedClusterUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ConnectedClusterUpdateViaIdentity(InputObject.Id, ConnectedClusterPatchBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ConnectedClusterUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ClusterName ?? null, ConnectedClusterPatchBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConnectedClusterPatchBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzConnectedKubernetes_UpdateViaIdentityExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConnectedClusterPatchBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ConnectedClusterPatchBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/AsyncCommandRuntime.cs b/src/ConnectedKubernetes/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 000000000000..38187eff7406 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,828 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/AsyncJob.cs b/src/ConnectedKubernetes/generated/runtime/AsyncJob.cs new file mode 100644 index 000000000000..b7aa1defa65d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/AsyncOperationResponse.cs b/src/ConnectedKubernetes/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 000000000000..2abac046e485 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 000000000000..03ac1140613c --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 000000000000..af470936ee24 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 000000000000..bab53ddc0873 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,99 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support"; + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!IsAzure || pf.Property.Name != "Id") + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = viewParameters.Type.FullName + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 000000000000..99838dcaaf4b --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 000000000000..69a2e99a2a3d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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.ConnectedKubernetes.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 000000000000..75a70c9f1fd3 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + protected override void ProcessRecord() + { + try { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append(@" +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +"); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder); + } + } + } catch (Exception ee) { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 000000000000..585df4eefa80 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.0"); + // 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.ConnectedKubernetes.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: ConnectedKubernetes cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.ConnectedKubernetes.private.dll"}'"); + + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.ConnectedKubernetes.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = {previewVersion}"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule ConnectedKubernetes".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/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 000000000000..f2af193a829e --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine(@"$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath)" +); + sb.AppendLine($@"$TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@"$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName +"); + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 000000000000..655dc1420c37 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 000000000000..82b888f2c8a3 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 000000000000..3b05eb58702c --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/CollectionExtensions.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 000000000000..aa37e47239b6 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/BuildTime/MarkdownRenderer.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 000000000000..9eb9fd5f190e --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + if (markdownInfo.SupportsPaging) + { + foreach (var parameter in SupportsPagingParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"### {alias}{Environment.NewLine}{Environment.NewLine}"); + } + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"{relatedLink}{Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 000000000000..943c71b7bdac --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 000000000000..9847d53348e5 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() => $@"{ExampleNameHeader}{ExampleInfo.Name} +{ExampleCodeHeader} +{ExampleInfo.Code} +{ExampleCodeFooter} + +{ExampleInfo.Description.ToDescriptionFormat()} + +"; + } + + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Description.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 000000000000..5fc3d5fa1365 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 000000000000..7d357a130900 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,291 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public string[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + RelatedLinks = commentInfo.RelatedLinks; + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (codeEndIndex ?? 0) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + if (Variant.SupportsPaging) + { + parameterStrings = parameterStrings.Append(" [-First ]").Append(" [-IncludeTotalCount]").Append(" [-Skip ]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string description) + { + Name = name; + Code = code; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}") + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 000000000000..a01981b231af --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,513 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BeginOutput + { + public VariantGroup VariantGroup { get; } + + public BeginOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}')) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + return sb.ToString(); + } + } + + internal class ProcessOutput + { + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + } + + internal class EndOutput + { + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new [] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new []{"
", "\r\n", "\n"}); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => new ArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, !isFirst && includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 000000000000..2eeb9d3ae922 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,499 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}To construct, see NOTES section for {complexParameterName} properties and create a hash table."; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines().Replace(complexMessage, String.Empty).Replace(complexMessage.ToPsSingleLine(), String.Empty); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[]{} : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + + private const string HelpLinkPrefix = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{variantGroup.ModuleName.ToLowerInvariant()}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => !ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)); + } + return parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))).ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/PsAttributes.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 000000000000..710289ff83f7 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/PsExtensions.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 000000000000..8d7bab5630dc --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal static class PsExtensions + { + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/PsHelpers.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 000000000000..1025d6a42aca --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path '{scriptFolder}' -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.StartsWith(GuidStart))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/BuildTime/StringExtensions.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 000000000000..809f6eeac60d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/BuildTime/XmlExtensions.cs b/src/ConnectedKubernetes/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 000000000000..9e7ba8b26d71 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/CmdInfoHandler.cs b/src/ConnectedKubernetes/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 000000000000..efb5228a743f --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/ConversionException.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 000000000000..4525dc4b1f4a --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/IJsonConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 000000000000..3d01629d8d56 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/BinaryConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 000000000000..575ca4fac5ce --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/BooleanConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 000000000000..ee10b0797870 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 000000000000..58ae2348f5e2 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 000000000000..1bf8b0e217a0 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/DecimalConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 000000000000..33c1cd4f00b4 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/DoubleConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 000000000000..b70b5cfd1c83 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/EnumConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 000000000000..98a2570b64c2 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/GuidConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 000000000000..392455b50a30 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 000000000000..d324a3361640 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/Int16Converter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 000000000000..703395aee279 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/Int32Converter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 000000000000..91b1034f9eca --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/Int64Converter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 000000000000..4dbb1890e464 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 000000000000..10e34a2f252d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 000000000000..8c861edf7fe8 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/SingleConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 000000000000..c93f9169a6c9 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/StringConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 000000000000..44088bf1e1c2 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 000000000000..8ba2ba714b4f --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/UInt16Converter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 000000000000..67a31928b77d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/UInt32Converter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 000000000000..d233a2c57865 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/UInt64Converter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 000000000000..e6d65c302c03 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/Instances/UriConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 000000000000..2b9163c6719e --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/JsonConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 000000000000..f5b0b7e32f96 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/JsonConverterAttribute.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 000000000000..0d743589e0f0 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/JsonConverterFactory.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 000000000000..59f50f9e68d2 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Conversions/StringLikeConverter.cs b/src/ConnectedKubernetes/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 000000000000..03ec22368135 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Customizations/IJsonSerializable.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 000000000000..d90a4a455964 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Customizations/JsonArray.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 000000000000..074bc59a7073 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Customizations/JsonBoolean.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 000000000000..4c2b12649d03 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Customizations/JsonNode.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 000000000000..4a1481b49a5c --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Customizations/JsonNumber.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 000000000000..972c597909db --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Customizations/JsonObject.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 000000000000..e2ecf46325de --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Customizations/JsonString.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 000000000000..1a76bfde78a3 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Customizations/XNodeArray.cs b/src/ConnectedKubernetes/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 000000000000..d7fec8b5ee4c --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Debugging.cs b/src/ConnectedKubernetes/generated/runtime/Debugging.cs new file mode 100644 index 000000000000..687a10e0e3c5 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/DictionaryExtensions.cs b/src/ConnectedKubernetes/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 000000000000..d8920bcce822 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + if (value is System.Collections.Hashtable nested) + { + HashTableToDictionary(nested, new System.Collections.Generic.Dictionary()); + } + else + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/EventData.cs b/src/ConnectedKubernetes/generated/runtime/EventData.cs new file mode 100644 index 000000000000..856c8da51fcd --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/EventDataExtensions.cs b/src/ConnectedKubernetes/generated/runtime/EventDataExtensions.cs new file mode 100644 index 000000000000..839466501962 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime +{ + using System; + + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/EventListener.cs b/src/ConnectedKubernetes/generated/runtime/EventListener.cs new file mode 100644 index 000000000000..a9fe9418080c --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Events.cs b/src/ConnectedKubernetes/generated/runtime/Events.cs new file mode 100644 index 000000000000..248d93084a16 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/EventsExtensions.cs b/src/ConnectedKubernetes/generated/runtime/EventsExtensions.cs new file mode 100644 index 000000000000..c97e178b8331 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Extensions.cs b/src/ConnectedKubernetes/generated/runtime/Extensions.cs new file mode 100644 index 000000000000..50af894d99f0 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/Extensions.cs @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + using System.Linq; + + internal static partial class Extensions + { + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => headerName == each.Key).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/src/ConnectedKubernetes/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 000000000000..6b8c198948e4 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/src/ConnectedKubernetes/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 000000000000..c817c76b2fcb --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Helpers/Seperator.cs b/src/ConnectedKubernetes/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 000000000000..98104fbc8a40 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Helpers/TypeDetails.cs b/src/ConnectedKubernetes/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 000000000000..bb27eb317935 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Helpers/XHelper.cs b/src/ConnectedKubernetes/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 000000000000..1335abe8e1a3 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/HttpPipeline.cs b/src/ConnectedKubernetes/generated/runtime/HttpPipeline.cs new file mode 100644 index 000000000000..90076319469e --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/HttpPipelineMocking.ps1 b/src/ConnectedKubernetes/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 000000000000..101e4ac30685 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/IAssociativeArray.cs b/src/ConnectedKubernetes/generated/runtime/IAssociativeArray.cs new file mode 100644 index 000000000000..cc428a823b4a --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + int Count { get; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/IHeaderSerializable.cs b/src/ConnectedKubernetes/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 000000000000..343813e1af72 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/ISendAsync.cs b/src/ConnectedKubernetes/generated/runtime/ISendAsync.cs new file mode 100644 index 000000000000..be608eb9a594 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/ISendAsync.cs @@ -0,0 +1,289 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/InfoAttribute.cs b/src/ConnectedKubernetes/generated/runtime/InfoAttribute.cs new file mode 100644 index 000000000000..f85868d9e5e3 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/InfoAttribute.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Iso/IsoDate.cs b/src/ConnectedKubernetes/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 000000000000..4933346a9c45 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/JsonType.cs b/src/ConnectedKubernetes/generated/runtime/JsonType.cs new file mode 100644 index 000000000000..e3aa35b5220e --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Method.cs b/src/ConnectedKubernetes/generated/runtime/Method.cs new file mode 100644 index 000000000000..e17d45fa3be1 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Models/JsonMember.cs b/src/ConnectedKubernetes/generated/runtime/Models/JsonMember.cs new file mode 100644 index 000000000000..d75eaabc307d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Models/JsonModel.cs b/src/ConnectedKubernetes/generated/runtime/Models/JsonModel.cs new file mode 100644 index 000000000000..f45f5a2eb466 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Models/JsonModelCache.cs b/src/ConnectedKubernetes/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 000000000000..5a6d25f5ae31 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/Collections/JsonArray.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 000000000000..ee8ab0ab5f10 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/Collections/XImmutableArray.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 000000000000..c59256ea18f6 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/Collections/XList.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 000000000000..5a00ae54cd30 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/Collections/XNodeArray.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 000000000000..728b253b1328 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Nodes/Collections/XSet.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 000000000000..1da05b5f14ab --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/JsonBoolean.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 000000000000..44740e909d15 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/JsonDate.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 000000000000..2c63ce1d1562 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/JsonNode.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 000000000000..98072c122bbf --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/JsonNumber.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 000000000000..e5fb53a4a1cc --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Nodes/JsonObject.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 000000000000..a006bc53ea82 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/JsonString.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 000000000000..93a9759db76c --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/XBinary.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 000000000000..f580f57127a1 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Nodes/XNull.cs b/src/ConnectedKubernetes/generated/runtime/Nodes/XNull.cs new file mode 100644 index 000000000000..e6e6a8dd1689 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Parser/Exceptions/ParseException.cs b/src/ConnectedKubernetes/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 000000000000..1917b1977b18 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Parser/JsonParser.cs b/src/ConnectedKubernetes/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 000000000000..c58db335500d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Parser/JsonToken.cs b/src/ConnectedKubernetes/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 000000000000..7cded0ab0a20 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Parser/JsonTokenizer.cs b/src/ConnectedKubernetes/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 000000000000..73eb5c7a2f63 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Parser/Location.cs b/src/ConnectedKubernetes/generated/runtime/Parser/Location.cs new file mode 100644 index 000000000000..3b9979cc29b5 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Parser/Readers/SourceReader.cs b/src/ConnectedKubernetes/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 000000000000..e5068837d583 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Parser/TokenReader.cs b/src/ConnectedKubernetes/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 000000000000..ea6e124c0ea2 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/PipelineMocking.cs b/src/ConnectedKubernetes/generated/runtime/PipelineMocking.cs new file mode 100644 index 000000000000..33fcb45f45fd --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/PipelineMocking.cs @@ -0,0 +1,254 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result); + + internal static JsonNode SerializeContent(byte[] content) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (content.EndsWith("==")) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content) }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content) }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"))) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"))) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Response.cs b/src/ConnectedKubernetes/generated/runtime/Response.cs new file mode 100644 index 000000000000..483ad9799d92 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Serialization/JsonSerializer.cs b/src/ConnectedKubernetes/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 000000000000..d878af4f0155 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Serialization/PropertyTransformation.cs b/src/ConnectedKubernetes/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 000000000000..bb444e68b106 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/Serialization/SerializationOptions.cs b/src/ConnectedKubernetes/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 000000000000..df6cda9eb117 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/SerializationMode.cs b/src/ConnectedKubernetes/generated/runtime/SerializationMode.cs new file mode 100644 index 000000000000..0e031edcc30d --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/SerializationMode.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeReadOnly = 1 << 1, + + IncludeAll = IncludeHeaders | IncludeReadOnly + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/TypeConverterExtensions.cs b/src/ConnectedKubernetes/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 000000000000..10cac5d1c1f7 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + } +} diff --git a/src/ConnectedKubernetes/generated/runtime/UndeclaredResponseException.cs b/src/ConnectedKubernetes/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 000000000000..4fb7a91683e2 --- /dev/null +++ b/src/ConnectedKubernetes/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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.ConnectedKubernetes.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Json.JsonObject; + + // see if there is an error block in the body + json = json.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // we'll create one below. + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/generated/runtime/Writers/JsonWriter.cs b/src/ConnectedKubernetes/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 000000000000..63be7b4c241d --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/generated/runtime/delegates.cs b/src/ConnectedKubernetes/generated/runtime/delegates.cs new file mode 100644 index 000000000000..8969a74ad873 --- /dev/null +++ b/src/ConnectedKubernetes/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.ConnectedKubernetes.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/ConnectedKubernetes/help/Az.ConnectedKubernetes.md b/src/ConnectedKubernetes/help/Az.ConnectedKubernetes.md new file mode 100644 index 000000000000..b11bd47e3b7b --- /dev/null +++ b/src/ConnectedKubernetes/help/Az.ConnectedKubernetes.md @@ -0,0 +1,25 @@ +--- +Module Name: Az.ConnectedKubernetes +Module Guid: 59df8ab1-442a-41ae-9b55-60b505bae789 +Download Help Link: https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes +Help Version: 1.0.0.0 +Locale: en-US +--- + +# Az.ConnectedKubernetes Module +## Description +Microsoft Azure PowerShell: ConnectedKubernetes cmdlets + +## Az.ConnectedKubernetes Cmdlets +### [Get-AzConnectedKubernetes](Get-AzConnectedKubernetes.md) +Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details. + +### [New-AzConnectedKubernetes](New-AzConnectedKubernetes.md) +API to register a new K8s cluster and thereby create a tracked resource in ARM + +### [Remove-AzConnectedKubernetes](Remove-AzConnectedKubernetes.md) +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + +### [Update-AzConnectedKubernetes](Update-AzConnectedKubernetes.md) +API to update certain properties of the connected cluster resource + diff --git a/src/ConnectedKubernetes/help/Get-AzConnectedKubernetes.md b/src/ConnectedKubernetes/help/Get-AzConnectedKubernetes.md new file mode 100644 index 000000000000..7155966cc9f5 --- /dev/null +++ b/src/ConnectedKubernetes/help/Get-AzConnectedKubernetes.md @@ -0,0 +1,202 @@ +--- +external help file: +Module Name: Az.ConnectedKubernetes +online version: https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/get-azconnectedkubernetes +schema: 2.0.0 +--- + +# Get-AzConnectedKubernetes + +## SYNOPSIS +Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details. + +## SYNTAX + +### List1 (Default) +``` +Get-AzConnectedKubernetes [-SubscriptionId ] [-DefaultProfile ] [] +``` + +### Get +``` +Get-AzConnectedKubernetes -ClusterName -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [] +``` + +### GetViaIdentity +``` +Get-AzConnectedKubernetes -InputObject [-DefaultProfile ] + [] +``` + +### List +``` +Get-AzConnectedKubernetes -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [] +``` + +## DESCRIPTION +Returns the properties of the specified connected cluster, including name, identity, properties, and additional cluster details. + +## EXAMPLES + +### Example 1: Get all connected kubernetes under a subscription +```powershell +PS C:\> Get-AzConnectedKubernetes + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +``` + +This command gets all connected kubernetes under a subscription. + +### Example 2: Get all connected kubernetes under the resource group +```powershell +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks + +Location Name Type +-------- ---- ---- +eastus connected-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks1 Microsoft.Kubernetes/connectedClusters +eastus connected-pwsh-aks3 Microsoft.Kubernetes/connectedClusters +eastus connected-aks-cli1 Microsoft.Kubernetes/connectedClusters +``` + +This command gets all connected kubernetes under the resource group. + +### Example 3: Get a connected kubernetes +```powershell +PS C:\> Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +``` + +This command gets a connected kubernetes. + +### Example 4: Get a connected kubernetes by object +```powershell +PS C:\> $conAks = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -Name connected-pwsh-aks +PS C:\> Get-AzConnectedKubernetes -InputObject $conAks + +Location Name Type +-------- ---- ---- +eastus connected-pwsh-aks Microsoft.Kubernetes/connectedClusters +``` + +This command gets a connected kubernetes by object. + +## PARAMETERS + +### -ClusterName +The name of the Kubernetes cluster on which get is called. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: Name + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. +The name is case insensitive. + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The ID of the target subscription. + +```yaml +Type: System.String[] +Parameter Sets: Get, List, List1 +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ClusterName ]`: The name of the Kubernetes cluster on which get is called. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. The name is case insensitive. + - `[SubscriptionId ]`: The ID of the target subscription. + +## RELATED LINKS + diff --git a/src/ConnectedKubernetes/help/New-AzConnectedKubernetes.md b/src/ConnectedKubernetes/help/New-AzConnectedKubernetes.md new file mode 100644 index 000000000000..b97779d83512 --- /dev/null +++ b/src/ConnectedKubernetes/help/New-AzConnectedKubernetes.md @@ -0,0 +1,199 @@ +--- +external help file: +Module Name: Az.ConnectedKubernetes +online version: https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/new-azconnectedkubernetes +schema: 2.0.0 +--- + +# New-AzConnectedKubernetes + +## SYNOPSIS +API to register a new K8s cluster and thereby create a tracked resource in ARM + +## SYNTAX + +``` +New-AzConnectedKubernetes -ClusterName -ResourceGroupName -Location + [-SubscriptionId ] [-KubeConfig ] [-KubeContext ] [-DefaultProfile ] + [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +API to register a new K8s cluster and thereby create a tracked resource in ARM + +## EXAMPLES + +### Example 1: Create a connected kubernetes +```powershell +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t01 -ResourceGroupName connected-aks -Location +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +``` + +This command creates a connected kubernetes. + +### Example 1: Create a connected kubernetes with parameters kubeConfig and kubeContext +```powershell +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t02 -ResourceGroupName connected-aks -Location eastus -KubeConfig $HOME\.kube\config -KubeContext portal-aks-t01 + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t02 Microsoft.Kubernetes/connectedClusters +``` + +This command creates a connected kubernetes with parameters kubeConfig and kubeContext. + +## PARAMETERS + +### -ClusterName +The name of the Kubernetes cluster on which get is called. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: Name + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KubeConfig +Path to the kube config file + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KubeContext +Kubconfig context from current machine + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Location +Location of the cluster + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to which the kubernetes cluster is registered. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The ID of the subscription to which the kubernetes cluster is registered. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + +## NOTES + +ALIASES + +## RELATED LINKS + diff --git a/src/ConnectedKubernetes/help/Remove-AzConnectedKubernetes.md b/src/ConnectedKubernetes/help/Remove-AzConnectedKubernetes.md new file mode 100644 index 000000000000..8a400c9bfa31 --- /dev/null +++ b/src/ConnectedKubernetes/help/Remove-AzConnectedKubernetes.md @@ -0,0 +1,263 @@ +--- +external help file: +Module Name: Az.ConnectedKubernetes +online version: https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/remove-azconnectedkubernetes +schema: 2.0.0 +--- + +# Remove-AzConnectedKubernetes + +## SYNOPSIS +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + +## SYNTAX + +### Delete (Default) +``` +Remove-AzConnectedKubernetes -ClusterName -ResourceGroupName [-SubscriptionId ] + [-KubeConfig ] [-KubeContext ] [-DefaultProfile ] [-AsJob] [-NoWait] [-PassThru] + [-Confirm] [-WhatIf] [] +``` + +### DeleteViaIdentity +``` +Remove-AzConnectedKubernetes -InputObject [-KubeConfig ] + [-KubeContext ] [-DefaultProfile ] [-AsJob] [-NoWait] [-PassThru] [-Confirm] [-WhatIf] + [] +``` + +## DESCRIPTION +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). + +## EXAMPLES + +### Example 1: Remove a connected kubernetes +```powershell +PS C:\> Remove-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t01 + +``` + +This command removes a connected kubernetes + +### Example 2: Remove a connected kubernetes by object +```powershell +PS C:\> $connaks = Get-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -Name ps-connaks-t02 +PS C:\> Remove-AzConnectedKubernetes -InputObject $connaks + +``` + +This command removes a connected kubernetes by object + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClusterName +The name of the Kubernetes cluster on which get is called. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: Name + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -KubeConfig +Path to the kube config file + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KubeContext +Kubconfig context from current machine + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. +The name is case insensitive. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The ID of the target subscription. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ClusterName ]`: The name of the Kubernetes cluster on which get is called. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. The name is case insensitive. + - `[SubscriptionId ]`: The ID of the target subscription. + +## RELATED LINKS + diff --git a/src/ConnectedKubernetes/help/Update-AzConnectedKubernetes.md b/src/ConnectedKubernetes/help/Update-AzConnectedKubernetes.md new file mode 100644 index 000000000000..7c112c73c863 --- /dev/null +++ b/src/ConnectedKubernetes/help/Update-AzConnectedKubernetes.md @@ -0,0 +1,207 @@ +--- +external help file: +Module Name: Az.ConnectedKubernetes +online version: https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/update-azconnectedkubernetes +schema: 2.0.0 +--- + +# Update-AzConnectedKubernetes + +## SYNOPSIS +API to update certain properties of the connected cluster resource + +## SYNTAX + +### UpdateExpanded (Default) +``` +Update-AzConnectedKubernetes -ClusterName -ResourceGroupName [-SubscriptionId ] + [-Tag ] [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +### UpdateViaIdentityExpanded +``` +Update-AzConnectedKubernetes -InputObject [-Tag ] + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +API to update certain properties of the connected cluster resource + +## EXAMPLES + +### Example 1: Update a connected kubernetes +```powershell +PS C:\> Update-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t01 -Tag @{'key'='1'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +``` + +This command updates a connected kubernetes. + +### Example 2: Update a connected kubernetes by object +```powershell +PS C:\> $conn = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t03 +PS C:\> Update-AzConnectedKubernetes -InputObject $conn -Tag @{'key'='2'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t03 Microsoft.Kubernetes/connectedClusters +``` + +This command updates a connected kubernetes by object. + +## PARAMETERS + +### -ClusterName +The name of the Kubernetes cluster on which get is called. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: Name + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +Parameter Sets: UpdateViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. +The name is case insensitive. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The ID of the target subscription. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +Resource tags. + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ClusterName ]`: The name of the Kubernetes cluster on which get is called. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. The name is case insensitive. + - `[SubscriptionId ]`: The ID of the target subscription. + +## RELATED LINKS + diff --git a/src/ConnectedKubernetes/how-to.md b/src/ConnectedKubernetes/how-to.md new file mode 100644 index 000000000000..574f3158a456 --- /dev/null +++ b/src/ConnectedKubernetes/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.ConnectedKubernetes`. + +## Building `Az.ConnectedKubernetes` +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.ConnectedKubernetes` +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.ConnectedKubernetes` +To pack `Az.ConnectedKubernetes` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://docs.microsoft.com/en-us/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.ConnectedKubernetes`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.ConnectedKubernetes.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.ConnectedKubernetes.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.ConnectedKubernetes`. + - `-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.ConnectedKubernetes` 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/ConnectedKubernetes/internal/Az.ConnectedKubernetes.internal.psm1 b/src/ConnectedKubernetes/internal/Az.ConnectedKubernetes.internal.psm1 new file mode 100644 index 000000000000..9b2b5e28ada3 --- /dev/null +++ b/src/ConnectedKubernetes/internal/Az.ConnectedKubernetes.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.ConnectedKubernetes.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.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/ConnectedKubernetes/internal/Get-AzOperation.ps1 b/src/ConnectedKubernetes/internal/Get-AzOperation.ps1 new file mode 100644 index 000000000000..16221b6394d4 --- /dev/null +++ b/src/ConnectedKubernetes/internal/Get-AzOperation.ps1 @@ -0,0 +1,121 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists all of the available API operations for Connected Cluster resource. +.Description +Lists all of the available API operations for Connected Cluster resource. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/get-azoperation +#> +function Get-AzOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation])] +[CmdletBinding(DefaultParameterSetName='Get', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.ConnectedKubernetes.private\Get-AzOperation_Get'; + } + $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/ConnectedKubernetes/internal/New-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/internal/New-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..9325a5825d04 --- /dev/null +++ b/src/ConnectedKubernetes/internal/New-AzConnectedKubernetes.ps1 @@ -0,0 +1,213 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM). +.Description +API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM). +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t01 -ResourceGroupName connected-aks -Location +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t02 -ResourceGroupName connected-aks -Location eastus -KubeConfig $HOME\.kube\config -KubeContext portal-aks-t01 + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t02 Microsoft.Kubernetes/connectedClusters + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/new-azconnectedkubernetes +#> +function New-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + ${AgentPublicKeyCertificate}, + + [Parameter(Mandatory)] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType])] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType] + # The type of identity used for the connected cluster. + # The type 'SystemAssigned, includes a system created identity. + # The type 'None' means no identity is assigned to the connected cluster. + ${IdentityType}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The client app id configured on target K8 cluster + ${AadProfileClientAppId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The server app id to access AD server + ${AadProfileServerAppId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The aad tenant id which is configured on target K8s cluster + ${AadProfileTenantId}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState])] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState] + # The current deployment state of connectedClusters. + ${ProvisioningState}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.ConnectedKubernetes.private\New-AzConnectedKubernetes_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/internal/ProxyCmdletDefinitions.ps1 b/src/ConnectedKubernetes/internal/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..7e21554c0b4d --- /dev/null +++ b/src/ConnectedKubernetes/internal/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,699 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists all of the available API operations for Connected Cluster resource. +.Description +Lists all of the available API operations for Connected Cluster resource. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/get-azoperation +#> +function Get-AzOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IOperation])] +[CmdletBinding(DefaultParameterSetName='Get', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.ConnectedKubernetes.private\Get-AzOperation_Get'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM). +.Description +API to register a new Kubernetes cluster and create a tracked resource in Azure Resource Manager (ARM). +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t01 -ResourceGroupName connected-aks -Location +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> New-AzConnectedKubernetes -ClusterName ps-connaks-t02 -ResourceGroupName connected-aks -Location eastus -KubeConfig $HOME\.kube\config -KubeContext portal-aks-t01 + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t02 Microsoft.Kubernetes/connectedClusters + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/new-azconnectedkubernetes +#> +function New-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + ${AgentPublicKeyCertificate}, + + [Parameter(Mandatory)] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType])] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ResourceIdentityType] + # The type of identity used for the connected cluster. + # The type 'SystemAssigned, includes a system created identity. + # The type 'None' means no identity is assigned to the connected cluster. + ${IdentityType}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The client app id configured on target K8 cluster + ${AadProfileClientAppId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The server app id to access AD server + ${AadProfileServerAppId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # The aad tenant id which is configured on target K8s cluster + ${AadProfileTenantId}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState])] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Support.ProvisioningState] + # The current deployment state of connectedClusters. + ${ProvisioningState}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.ConnectedKubernetes.private\New-AzConnectedKubernetes_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Description +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Example +PS C:\> Remove-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t01 + +.Example +PS C:\> $connaks = Get-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -Name ps-connaks-t02 +PS C:\> Remove-AzConnectedKubernetes -InputObject $connaks + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/remove-azconnectedkubernetes +#> +function Remove-AzConnectedKubernetes { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.ConnectedKubernetes.private\Remove-AzConnectedKubernetes_Delete'; + DeleteViaIdentity = 'Az.ConnectedKubernetes.private\Remove-AzConnectedKubernetes_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to update certain properties of the connected cluster resource +.Description +API to update certain properties of the connected cluster resource +.Example +PS C:\> Update-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t01 -Tag @{'key'='1'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> $conn = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t03 +PS C:\> Update-AzConnectedKubernetes -InputObject $conn -Tag @{'key'='2'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t03 Microsoft.Kubernetes/connectedClusters + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/update-azconnectedkubernetes +#> +function Update-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + ${AgentPublicKeyCertificate}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.ConnectedKubernetes.private\Update-AzConnectedKubernetes_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.ConnectedKubernetes.private\Update-AzConnectedKubernetes_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/internal/Remove-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/internal/Remove-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..b3153b1683af --- /dev/null +++ b/src/ConnectedKubernetes/internal/Remove-AzConnectedKubernetes.ps1 @@ -0,0 +1,182 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Description +Delete a connected cluster, removing the tracked resource in Azure Resource Manager (ARM). +.Example +PS C:\> Remove-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t01 + +.Example +PS C:\> $connaks = Get-AzConnectedKubernetes -ResourceGroupName azureps-manual-test -Name ps-connaks-t02 +PS C:\> Remove-AzConnectedKubernetes -InputObject $connaks + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/remove-azconnectedkubernetes +#> +function Remove-AzConnectedKubernetes { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.ConnectedKubernetes.private\Remove-AzConnectedKubernetes_Delete'; + DeleteViaIdentity = 'Az.ConnectedKubernetes.private\Remove-AzConnectedKubernetes_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/internal/Update-AzConnectedKubernetes.ps1 b/src/ConnectedKubernetes/internal/Update-AzConnectedKubernetes.ps1 new file mode 100644 index 000000000000..e5178293b4ca --- /dev/null +++ b/src/ConnectedKubernetes/internal/Update-AzConnectedKubernetes.ps1 @@ -0,0 +1,183 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +API to update certain properties of the connected cluster resource +.Description +API to update certain properties of the connected cluster resource +.Example +PS C:\> Update-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t01 -Tag @{'key'='1'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t01 Microsoft.Kubernetes/connectedClusters +.Example +PS C:\> $conn = Get-AzConnectedKubernetes -ResourceGroupName connected-aks -ClusterName ps-connaks-t03 +PS C:\> Update-AzConnectedKubernetes -InputObject $conn -Tag @{'key'='2'} + +Location Name Type +-------- ---- ---- +eastus ps-connaks-t03 Microsoft.Kubernetes/connectedClusters + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the Kubernetes cluster on which get is called. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. The name is case insensitive. + [SubscriptionId ]: The ID of the target subscription. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.connectedkubernetes/update-azconnectedkubernetes +#> +function Update-AzConnectedKubernetes { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedCluster])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('Name')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the Kubernetes cluster on which get is called. + ${ClusterName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [System.String] + # The name of the resource group. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.IConnectedKubernetesIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [System.String] + # Base64 encoded public certificate used by the agent to do the initial handshake to the backend services in Azure. + ${AgentPublicKeyCertificate}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Models.Api202001Preview.IConnectedClusterPatchTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.ConnectedKubernetes.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.ConnectedKubernetes.private\Update-AzConnectedKubernetes_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.ConnectedKubernetes.private\Update-AzConnectedKubernetes_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/ConnectedKubernetes/internal/readme.md b/src/ConnectedKubernetes/internal/readme.md new file mode 100644 index 000000000000..981ae176cda1 --- /dev/null +++ b/src/ConnectedKubernetes/internal/readme.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.ConnectedKubernetes.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.ConnectedKubernetes`. Instead, this sub-module is imported by the `..\custom\Az.ConnectedKubernetes.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.ConnectedKubernetes.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.ConnectedKubernetes`. \ No newline at end of file diff --git a/src/ConnectedKubernetes/pack-module.ps1 b/src/ConnectedKubernetes/pack-module.ps1 new file mode 100644 index 000000000000..c22fad33d87b --- /dev/null +++ b/src/ConnectedKubernetes/pack-module.ps1 @@ -0,0 +1,16 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/ConnectedKubernetes/readme.md b/src/ConnectedKubernetes/readme.md new file mode 100644 index 000000000000..04798d348625 --- /dev/null +++ b/src/ConnectedKubernetes/readme.md @@ -0,0 +1,90 @@ + +# Az.ConnectedKubernetes +This directory contains the PowerShell module for the ConnectedKubernetes service. + +--- +## Status +[![Az.ConnectedKubernetes](https://img.shields.io/powershellgallery/v/Az.ConnectedKubernetes.svg?style=flat-square&label=Az.ConnectedKubernetes "Az.ConnectedKubernetes")](https://www.powershellgallery.com/packages/Az.ConnectedKubernetes/) + +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 1.7.4 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.ConnectedKubernetes`, see [how-to.md](how-to.md). + + +--- +## Generation Requirements +Use of the beta version of `autorest.powershell` generator requires the following: +- [NodeJS LTS](https://nodejs.org) (10.15.x LTS preferred) + - **Note**: It *will not work* with Node < 10.x. Using 11.x builds may cause issues as they may introduce instability or breaking changes. +> If you want an easy way to install and update Node, [NVS - Node Version Switcher](../nodejs/installing-via-nvs.md) or [NVM - Node Version Manager](../nodejs/installing-via-nvm.md) is recommended. +- [AutoRest](https://aka.ms/autorest) v3 beta
`npm install -g autorest@beta`
  +- PowerShell 6.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g pwsh`
  +- .NET Core SDK 2.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g dotnet-sdk-2.2`
  + +## Run Generation +In this directory, run AutoRest: +> `autorest` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +``` yaml +require: + - $(this-folder)/../readme.azure.noprofile.md +input-file: + - $(repo)/specification/hybridkubernetes/resource-manager/Microsoft.Kubernetes/preview/2020-01-01-preview/connectedClusters.json +title: ConnectedKubernetes +module-version: 0.1.0 +subject-prefix: '' + +identity-correction-for-post: true + +directive: + - where: + subject: ConnectedCluster + set: + subject: ConnectedKubernetes + - where: + variant: ^Create$|^CreateViaIdentity$|^CreateViaIdentityExpanded$|^Update$|^UpdateViaIdentity$ + subject: ConnectedKubernetes + remove: true + - where: + subject: ConnectedKubernetes + parameter-name: ClusterName + set: + alias: Name + - where: + verb: New|Update|Remove + subject: ConnectedKubernetes + hide: true + - from: source-file-csharp + where: $ + transform: $ = $.replace(/\).Match\(viaIdentity\)/g, ', global::System.Text.RegularExpressions.RegexOptions.IgnoreCase\).Match\(viaIdentity\)'); + - where: + verb: Get + subject: ConnectedClusterUserCredentials + remove: true + - from: swagger-document + where: $.definitions["ConnectedClusterAADProfile"].required + # remove: true + transform: >- + return undefined +``` diff --git a/src/ConnectedKubernetes/run-module.ps1 b/src/ConnectedKubernetes/run-module.ps1 new file mode 100644 index 000000000000..11e3b72d0c88 --- /dev/null +++ b/src/ConnectedKubernetes/run-module.ps1 @@ -0,0 +1,59 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.ConnectedKubernetes.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/ConnectedKubernetes/test-module.ps1 b/src/ConnectedKubernetes/test-module.ps1 new file mode 100644 index 000000000000..0772c960f041 --- /dev/null +++ b/src/ConnectedKubernetes/test-module.ps1 @@ -0,0 +1,68 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Live, [switch]$Record, [switch]$Playback) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts:$false -Pester -Resources:$requireResourceModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) { + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.ConnectedKubernetes.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +if($Live) { + $TestMode = 'live' +} +if($Record) { + $TestMode = 'record' +} +try { + if ($TestMode -ne 'playback') { + setupEnv + } + $testFolder = Join-Path $PSScriptRoot 'test' + Invoke-Pester -Script @{ Path = $testFolder } -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") +} +Finally +{ + if ($TestMode -ne 'playback') { + cleanupEnv + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/ConnectedKubernetes/test/Az.ConnectedKubernetes-TestResults.xml b/src/ConnectedKubernetes/test/Az.ConnectedKubernetes-TestResults.xml new file mode 100644 index 000000000000..9bac639c3407 --- /dev/null +++ b/src/ConnectedKubernetes/test/Az.ConnectedKubernetes-TestResults.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ConnectedKubernetes/test/Get-AzConnectedKubernetes.Recording.json b/src/ConnectedKubernetes/test/Get-AzConnectedKubernetes.Recording.json new file mode 100644 index 000000000000..93dd8b05f634 --- /dev/null +++ b/src/ConnectedKubernetes/test/Get-AzConnectedKubernetes.Recording.json @@ -0,0 +1,197 @@ +{ + "Get-AzConnectedKubernetes+[NoContext]+List1+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "9" ], + "x-ms-client-request-id": [ "37585a64-d06e-48a7-a182-35c1cbc9dce4" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_List1" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11996" ], + "x-ms-request-id": [ "a94e7734-19ad-4b7c-9cda-e830b00efbb2" ], + "x-ms-correlation-request-id": [ "8277f1f4-6a0a-48ca-ade9-04b74993d061" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022455Z:8277f1f4-6a0a-48ca-ade9-04b74993d061" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:24:54 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "15117" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/wyunchi-aks/providers/Microsoft.Kubernetes/connectedClusters/wyunchi-aks-cli1\",\"name\":\"wyunchi-aks-cli1\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"dbf416fc-aa21-4396-989e-ef4ddff4d720\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAtMKL7ef5KzaChkls6QLRZsmhkL4tvRwj52zqJMDOCALKzlbNMA83vK4loKlawUaZ46NU34iRQhfL/QyRY/PTezUO8y7yguhdFt8H3JyYZF9e6eRIJkvXwE4EGz5Tlh4HPKZ39xxdnlHZClhcqjzCZ0CWnyDS9UtMu8mgiHoC3p2K9XMEVFmnybUpy2tCn9Xd8NXsISRAh9DguIMF4XBgKlEiGuactT3XptHNfAkvI2E9XHnU3dPQMcltUxD2BVXtJhCJMlMtNIMfb2Xvz3ojWbN7Hl3iepJrED2FplYdYaFgqHiggy4+uNaNDLtsRQjj0mIHASk8d9PpFw1vL3HC6M7cd+ezrh6wmnYKhgHE7ChA8O+8KwMfe0+qILodzhvqhej89EaXV8dfuLWPxxfaAnfyozsITv0e2XJf/zsJLTwEL/73fLsZrDEdf5oiskAajZXSQ5mpCaCnCUmb3DgVTW8eQZC2TyWFcqiiO7keaMGsDkVrpZ95l/Ifwido9r/rPRT2x7JVkyXtcaFX/bOyXyFKFVnhzOCBeWViWqtyixhVIhqgn96bi+TqCkIx7fGvAG4MbTC/5cFl+Jz1u8h40HUYntL5I6plwJNWJtyCPA/n7CD2YKt+cio83uEjX5jWLx1I/UjLlojC7Ojg4UrEX9Qfq+FIphvmUIVQvD0TBqsCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"},\"kubernetesVersion\":\"1.15.11\",\"totalNodeCount\":1,\"agentVersion\":\"0.2.4\"}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/wyunchi-aks/providers/Microsoft.Kubernetes/connectedClusters/connaks-ps-t01\",\"name\":\"connaks-ps-t01\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key\":\"1\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"24d7af88-7735-483e-a079-5cbbe122da96\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"r+I/UjOFZGl6Cx0YJz3J753Hk0vBj4Z1D44kj4VpZ8rLHQOmy2eQannteo7VD3gXOzxkD8LZ0As2yCgmPxhjfho+e09Dq/Ue1Pm6KnTmcdeuLa+AYhibvBuH35zaEXEdFrWFtavalOjG4Gd4xYlkl0aWUt6/WovNODAe4XC0biJCEMWD/gCo9HFPfGcIV+Qg3UXTTTvw3KqZEDg7xZyi1KgQuBa8E6hekaKcwTz+BF/oH11sWZjsBIeRicZoK/vpJCKt0bj5aIXoOpKVeshmvroTpG75AklT4VrvK1Zjw/k49tj/YTPVbz+mKdEqWDGaxA/XZVCI7cxikBkS0pJxmUv5dD6upHEcjin5LABBdxjvUCYiXQgC3luyu6KvsxCV+J2VW9mSLyvCuY0UaierDvG8syMf+7B0Q0rZ+zX/EX5yQ5KnBr2BRG5UHJIZloepPSkFHbJX5sgMRCqPVD5/3zd6E++oW/9COmpgAr2WWlczohV426pC0btO2c5ooezrqMnDoqOb/RY1/7gtcpgBbVDYINjvbp7jgNzNBJo9DWvu0A2KCVPx7IkX4xMGDNfy/kOM4KGLVwyxUL521gXezUhD7aAaaFdnrNGqxynvycZoObly3I90cvjaGPkSfHFRQhBr3jLo+AHZON08z066gdvhmZwFVcFUmdtMOxEXirc=\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/lucas-aks-rg/providers/Microsoft.Kubernetes/connectedClusters/connaks-1yvutf\",\"name\":\"connaks-1yvutf\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key1\":\"1\",\"key3\":\"3\",\"key2\":\"2\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"b9edeef8-48ca-4a02-9112-ee89c3f194d3\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"1O4LKFj3yK/iCztdmrRB4llNhbIvB2K/j3eisEGpHGHh1mLxYlPwCIOYj53to5dp+WLoQYwk1ZteqM6dFSUxAHSeSDYmR5voQ6GRYvxY4Eh3vYE86/D7zDXVL42Tlx4jBy1A24pyqMZ3pKAfl0E8jCyt0JXPgKY00J5rHjpBQW/4T7bw1iPUkNVi3D3UrnEk3Z0HVwCNT8uu4fRWA7t37YVh20dxtH9RgLvtyohKdBkHYQxQTLfeRrvMDOvHB7TUWRqfLE4rlokEXnCD5A/h72SQ2yErDOZQYhfUpZkoAE9Gt8/1dX4bs0s8pQ0WZkbKkTFKg2SdQ2tQSP9iaS6IcB3Bdb5DVj5sqRSqWRAyVXqrXxo36CwZ3xQ8R9JA8qXmCF4uX5Lz38OapD9w0CQA4BuzCvFAPgWho6V47TFWtmFKLyLm6QwFYTzRb/nIutEe9SWVy2oThPhrVc25Nm8F9Gbvj2puVgcsmIEoU8CW56emg5fPJ1LmBaDDgLWnhYevBx/RpGFcZ5tiRFHYnENuAjw5/F7iwEqdyFjt1gNJ2i/Mu9kw0tM624YkrfKGsBBHc5d8Pa+qvfPzbXbHhGEXDWtTQRy0cwhVoiVzrCHiNOsInFCvtzs2Di5WswFTcfm/6fsARuPN9om7CSer5l1BLxqO/9L4tl6k6ih7V3zSot8=\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/wyunchi-aks/providers/Microsoft.Kubernetes/connectedClusters/wyunchi-aks-cli2\",\"name\":\"wyunchi-aks-cli2\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"223aa170-b253-4634-acf7-40f714d0cff4\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAlJD/FwyMqPzVmheKsIN6iuJ9m+Io5z6UKT+yYKv/lYhFQLH2fBlulGcgIpvO6GxQg3EklKPby3lHyZDIIEfHdB2TTFOBHdHMSy3EbTcxsc66ZeFOBzfg3FqMqgUVmCdZi6uK0LVD4ZbUI1ayW/+y/VCHjtR0FDwR2AtnWen4zfKjMMnrTPx/8dgR7dh7n/3PkvbsedDMKTK3vlkQponEktGQbm4csmcWe7ggUJSBkHAQZjRk/o9ZSWOM0Oowkd5zw7gbnMpScQPWit7kwWQzXnVNUbk8EYJPt3d/Y7LUkLvfJySSFmk/6eWX4vJ4F6HryLmiQltK0nBaFH9iY3VkIoEtUXwCPkpMHk2hSSptAV6+KMABlZoWGfsdtl+8fY1VW/u7AfS8TLIQm06CSa+fvLCOLXrCd+PxUOouiRlYThkkvXEU4IfwEAbhmpxl6O60sJzloukerOq39C14kPhe0/xnRLZJpUJzC5Z+I81meZcpnjsOEX9ZmrPKU+DqzJbY0//OyRaWJTUpiTpd0ZLUuIwjBprTWCAjUJ9szo5ooM+jg2pPOGI6WKmEbvmxc/+8En8sVfotmxqS9q9y66eI5RWnfzsLpGayZhSqneWuRFejw+KgWzuI5labwqI4nLDMhaAoywY8pcZ3nIshurwQv73jN8t6+PMCi+0ZjslTRtsCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"},\"kubernetesVersion\":\"1.15.11\",\"totalNodeCount\":1,\"agentVersion\":\"0.2.4\"}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/wyunchi-aks/providers/Microsoft.Kubernetes/connectedClusters/wyunchi-aks-cli3\",\"name\":\"wyunchi-aks-cli3\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"26ab96e3-b302-43ae-9ec9-cbd803184815\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA1oB+ONV8P887Ik6m3+ffgDpybXvg8V1Re8eXIfdZiB67osH1UeEcXxWIVG2D93XQ5RR8RPJxCYd9dI5Gsw0pXESEWo1PSOeeGpcCpidxD+rxFnydBw/Bzh4jHmR8dk4pC/PiFG8MTcuM23nWCLaLsOqMLlBn/QHGU4r3iES4l/hP0QUmKbuV3WOCdO2OcWv0NdluMHPkbSdt6a8EW+HQ+qSMLRg6jaZfQ66RV7s49rvW9HBDMnHgFGuiu2aixNnJzijpVKgQ6nbdwL+UJuUhDgJ/EZ8dic1UfN4OchWD3i+POdfm/q1QJzDigyuq05ZQIfWOPdS9MfHSqOlh//47MvOzCqsp9Vo0O+Lr3vpORKQ7Lvffipj/ArihUBGJXqmNGvFDnpGUN1BU/oAPkUH2iVS6fC+J9D89XxRB/iOj9Cd4inJriETIlDdLfYuFuMnBZSgSHT6JcQr9IU/pnKp3P8qkk50p/vxZtZOy9CyueUUBOLRVyx7L92Y5QIGZuz36Txk6PpsxOLKdKOX/3amHNPx1HnIeN5d3fKzuB9unKv9YM9NVgR++B3uCMZh0omm0PMAciFfpTuHJ3GzcF1un5qLVVUz+ay/tuZSrB5Ln5Cb6yZVp3nYyCKybHDnmTKcK7kgYJxSx40u7WKeII6IY743+jYOpNXudkI0YDjAl/5ECAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"},\"kubernetesVersion\":\"1.15.11\",\"totalNodeCount\":1,\"agentVersion\":\"0.2.4\"}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/azureps-manual-test/providers/Microsoft.Kubernetes/connectedClusters/ps-connaks-t02\",\"name\":\"ps-connaks-t02\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"eb940248-1db7-4524-a98f-2b5cf24d3800\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA+Yxn//L42VxmjX0hVPPzXBhJ7s/WvM5LVN0oPeGOK5M0KrYai/jafXcXWTO6/cVRE9h1TD4lsq0kMx0TiqKbPLe0HH9AXq5MEPd5NVdYc6lxCKxy7C9V85sLq65/aq7PpuYVCvfCU6wv03FfVKzDjB3yBfY+32UzwU/bzcwKRE3pFJOYSq/n9J6EG9/Fk4iORhqSn2H+eHdRixE231KEkT2EnIqfo8itiGQ27abZlo8qDNzvtDBXq28iPbFF4Ek258zAeZdkz7GCdoKSrGMx7/gxxYeAgReHS0kGFR38ZO9UY/CzhkcvTo8M8Vhm44IR0X9adtoxfURQcw6aAoWSpfHpJnRvrtXJz//1M3GDsiQwOUOPW0EegmA8b2hZL+STyOE1JYdy+Uvxa+VIwWOwJbVzUbJrUeSTPvVugeuvhMEpmKDI54Xde9/cq96GWBuZom1MVStk4Arar/BBgRE6C0HWXKWJ5lA3VNtB6yQKm8zxqShcqSqAZ3ctkjnxLZkvbz7E+CgLRQfqbu+I1SMaOJsvHWdz+SXCPGKCQ8nesmMLLyBQmge+cvnEGrZaRH015t26OrdWJtjqVSkzmCS8P//T+XjkKMOIPibKf/Dsk0pSu77VUYQELpwDiULL8cpe9Ji3UqyiHALTTgZ4CRHaQxIszTu0nNePZRt9gZWubpMCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/azureps-manual-test/providers/Microsoft.Kubernetes/connectedClusters/ps-connaks-t03\",\"name\":\"ps-connaks-t03\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"2b977490-324b-48ca-a369-d5b2453b6922\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA0hM8j9z60eMG5LDCY8qoWvh9AZciqRvwl1hvqiOOK22iwo3OOM5si3I4pWoAh8L3sM0gAfbc5R9Izg4YYFT0R1iF/gIr3at7nKRVaYol90iRxE1LTbmRss9gWLmGc5T3H17YKy+GFg2h6tm/sIgUsAMVdIW7VYEbu+b7BcNK6odrFWYcbSTt6hAtRzENwQd0bC8gLN14mndMw6HFL+wwJpULV350gb8C0d1sjTIcVBty3q89aBklUpSJyHWmyybbQRc/QyNomk4YQsZKyTaS1tLle9AMOI+fhL8xkc4WG04qh8s603WJAbhVVaqrTFuQfUfVqdKd4HlIQFCAQ/GBTE0ub1GScWn92YI/F8alj2ORNjFMzIwpQMrOB316WiYAMT7otJ7QWqigN646zOdREfaw3psyRXpRzEDS0E0JsKp8RJ1LzwuY/5Yop16R4+HVp4GHn12j6qvCzvsw2jA6mSfA4Kq+a2BjaLsvTazpnBF4BMXWFfIJ+3a/jkPhl551I0COWiaVvr98jf5BrsRRlAOQ63N9+0ySncK8MIC0ywTg7xXi2dmH789KzyqBN0Oi4INcAy265duquEl1yZFlV/eSgj4sjKF4uw84p+YgsN0ShUmWlF5hg1oAiulDdcJZZPOEtX32D6z13tVWPwogyd6QZjveSQrQSNy0S+3YREUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/connectedClusters/connaks-d983yc\",\"name\":\"connaks-d983yc\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"837f6682-219b-406f-a158-9a8738daf39e\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA7kLLoI6CW1NgGgV7iC3m7vb6vKa7azSFse9UgUcxFUb+p5ceN7VqpnwTenkAW+dkF3E5Gg5MqacnCrLghKGBrUUAahA4HNznNE409owGj3l6vJPV0Y+buftf9LESnWleS0t3sR0XSEZanhH45aKMpJA9DErEjIAgFlqZzg+aHv3j2183neLehAsRYU2sNYXU7VpTV7yESPIiEWD5piEPtzuKZHoWudn7uuFcHzAdj7dd66zwp3UQq9b7HKnsSm9+jZ+/9XX8o4tm+gH8fWJwU0fJT2voMqtXtyRe4BL3zwjiH3cNlMQ7gcSrHM3nG8gbfpJ4KlvHltqAfBubq02F+bAsBJB87akBSMOmTKnBSqPfaJObeB8AR2ZJ1j+/prztCfm4l7wXaHYLip+JQqswTsM1zWzANwTJ9kzumldXinpSc1zF3QxCedPyoQEmkH3LQiQRW6Pa0TcYkNs3VkeLJ/Si6eK0BESpEljLVPUtMiJsQpfaWgVpNPUApSff/h2TCP8YN9o5nO0GjWjuuz2VcpgRYIShfYUGxD7MJkH2v+ABpPhzbGS+hSPfBydWppDOr1GzbJSAIBONz3lU8vOkqbYYlheEHZByUEeVS1+XVKAZ/Oqb2aNg/PlCSl020NqvMFZe2X91nUeic3+bfABROsimu98lh/PybXClkBnoeNECAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/connectedClusters/connaks-dsc3dc\",\"name\":\"connaks-dsc3dc\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key2\":\"2\",\"key3\":\"3\",\"key1\":\"1\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"4893b3d0-0abf-4b68-9916-7c7c1717feef\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAwaUbM1YL9YNdgLn/VaGJM0tlKGiTYuGnp3/XSnYC81KkRbFZZRV3TEqDNV+2QH8n07BxqMnT13ddsBrzDZp4teDD6dkwaTUT63A1KpHSz77LKbikNyuc9qg+XamNIE3REEXMFbinka/VFR236vaS3ObEXQHnMl9VYqcjZ+t4eGuZtDB/s3foFWK4K4wuF0RhZomy90TM5LVlWEXPxCpn1Zbg/nvJZuF8MevnCiU/i+WcYIEdb1Aj752imIhHtRRQV5UhbeIn4I75LFJXqBxhcjCKrw00qmX+M5ltr2txv3pfc0CA+g+SYAfWdP1eZOiDLf7FkaHO1MOj888GmDPErZPJ+9UMPHZUOP4Rzpdiwk2HRzxG12NLwQ5Nav2TMyRRzrQrVVqc42HTpd1HrnaW/BlxYVQxVZGYlfOpeQ+y0P92eZA4GZYrcuIO7VQ6D8rOUEXeGeyJytJxfiXvHfI68RD1EEI0xXEKeAIexjABRZ4pReffyupIEqCNu25TMPrCrkIUwcSyS2Y21xlB0UWu6pfyk7Gjbxzs+5dSwGoKAWbNaGTZqJyWnZWeJnoKxDiNBzMYl6dLzEAHDcJLRc5/1yUhOKMUBKq0QBcUspzwmDTiPl2ktrKx+/19fgH2tq3AAG+x9kQDDYeAGOE4tyouXCSz0+DX7OuUObROaynSSVMCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/connectedClusters/connaks-dkc29c\",\"name\":\"connaks-dkc29c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"c8d110f5-161f-4db4-9c56-8a15e0099e3c\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAv2vmYgV784FUgY2cOToYOUUl1yVvX0NpSYPMYZl83y/QmXHpWyG5J7EX+ldrgLkMggGBwToBcCCNSRB8+k746UlpS6s34W2EoQH7Z9krJGMd6QNpX+uftKWy2wtt9BBnmGRkwnRCiWvc7b7R3sayg3UFNma9S5yzsbV+ZeHpiCZLeLM8lKgM8ZaHtHERdYd/Tt6QuFbet5cmNAi6IjyPmrjHieHPrSt0rj3NfrvKmIjn/u/mErOf79MOJA0gxsXdAAFEGXKek06t5cTZsjdB/HfMVZ1IhXxT2XifrUJkZ+XugPcEEDmSMAaf7qxqjl4zjsqxq6mGbp59/S4aVJ+J5gTcaeJ0I1HRgxttJqbzi5TTsvp+RBdyWNoBOZetblqsveN7z/1DvIPoxoBuH77mu4qwTIhVVug8WJYs7Mfb2+M7Gw5k2eoCp3jZNvKZ/gp6XtxXmt+wrNQgx6Sm013hCeDpqqDvqe5m7W+TA0SyVD+cUnhrCYwTECc9gE1Lk2RPRj3UenwVuhpmddScesCGKomoumU+WOo6omjaCKO/LCcH+2xbjqOCUCm4YgXG7rPX/waI39j4xj5PyA7CGq2xKODKajHu1QkV0HWrN1NOsXKiqOWsKCwcHbESQYldMewXfhEtZqGEf4eBPugHQw0NmEiymrTdXRIb1VewC8X76p8CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c\",\"name\":\"connaks-s25w9c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"928ddda8-d0c8-4305-bb86-bf23b563de80\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAm/3yDiP5tp78mOXB/vKO6w80pKIEbUfdXsq70i/ssv7N22oMbF+lxOJydclwKrB2jekN+S3lfJd8HfQBnqycsOHEPqVLupN3VGiipKpJekthOeTSRAgFF3t6rc5e9Js/LBg0zfJlVMTni3sV4VU8wS9AGpOIM7CX6ctWgsi/5xkxm3dTpynnuho+s9FdJokkoohWkB1fF/0hMgBBKgtZIKRB343Mkk/2meunnqy5O+E2/IIQf00gf14b7vLKxAY/OdQSgpoD0LIUGNz93K4FQaI33i1GjJWdjPzOtHAI2GZUuiVu4mM/v9DtUABwQefiK05u9vqtejWfoUzG6TNHxpjYv/pFguDNmPwDHzPhxb4XvwmX82qVDVYQBZhGmAcEIrgJ1XUTfy/f7WPh0OBTi+T995pQS87YSMSXbGTvzooSypac2YA18zCBCo3mSDhMGblvKHfvKAszSYQCEQ/WR3D0jbhxaNKU/nk+hkcbtWQvYvdzZ5dxkEfi7K+CHFGjN7owf1veTl8fCbCPS1MVgJGi5M477u6K4k04SOI9IACOcwpi1vkyTupEypzJyMb+mZG4+VkhZMKSIbeUkG9KWDz+q3VnuD9OW0138iME9AXGulHiB8wr7GgBXoOJIzdF3l11CcZMRYdgG1vIR8BQn6LdgyEz7ueFHVSNSq3Twc0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c\",\"name\":\"connaks-ep8b1c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"91ac6d50-da2c-4621-890a-b4de9a199c98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAqihH1cAkW/NV+Olp8/3fMYPUabrhqX2VLfPbv8FiIS+zBBFm+V85qn4QuFu0pIkMYLxbbOfwb2vEqFHu+x82LS/8YoMkgoDNmywG7wuKeSuKQC627cLL47DLPRsdsD8wI7IkkxVDUF3bczStRKp89YaTQvPT/kHSu7jYH/K7ViwKH34/ftY8iGz7yjpGVglYW6qDZ8x4PcE2uZsmgY/v86G5h8kcidOW3GsGtABw7v1ZTPi4wyYVWFrrvt45ZOQV8TMqz7adCNhDDRfo7xcrSqOp0bvib5l5SHh+4+PNPvcda7aRnZEA/mVqKU5KnlqAUOPaWNi3O9SfeXgt63Y73jbGYcPJREPEJeR1om3JEkJLM2BqbRqntW5+LpJv/l/XKsAnFD5XJEd0QEnN4nKs++huTPorPOBpqRbe5yoKI0m+JUlpGX1C2A+gAJS1GCqY+HkjkxtfZmCiOT8MwVWPOv7iM0NHn7RrFAXWLkKjmHtuNsI/hOR/YcIrz4qBFH8KGohhAESAZiN8GySpsDwYk3XXsKa2FdcPy28Kpyrhn13Nk5y8+AV5fy3/kUsD32PqJbfA3vJh/WiPgviHs2k5XehJlVh8K/vN6aA/sxNXKyFvoN1C9XQ4ZGpxwisJ0tk5DEhnnwmuYOwh1baH9cfUKQkQ/ESK8Fuy/CicBf3ZYv0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}]}" + } + }, + "Get-AzConnectedKubernetes+[NoContext]+List+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "10" ], + "x-ms-client-request-id": [ "cb430682-b14f-4cb1-9378-b7c6000b06fd" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11995" ], + "x-ms-request-id": [ "d9891f67-9873-4d9d-8f30-18b44ddc8854" ], + "x-ms-correlation-request-id": [ "5c24df9b-9d57-4401-b9a5-912f08fa2ff9" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022455Z:5c24df9b-9d57-4401-b9a5-912f08fa2ff9" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:24:54 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "2481" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c\",\"name\":\"connaks-s25w9c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"928ddda8-d0c8-4305-bb86-bf23b563de80\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAm/3yDiP5tp78mOXB/vKO6w80pKIEbUfdXsq70i/ssv7N22oMbF+lxOJydclwKrB2jekN+S3lfJd8HfQBnqycsOHEPqVLupN3VGiipKpJekthOeTSRAgFF3t6rc5e9Js/LBg0zfJlVMTni3sV4VU8wS9AGpOIM7CX6ctWgsi/5xkxm3dTpynnuho+s9FdJokkoohWkB1fF/0hMgBBKgtZIKRB343Mkk/2meunnqy5O+E2/IIQf00gf14b7vLKxAY/OdQSgpoD0LIUGNz93K4FQaI33i1GjJWdjPzOtHAI2GZUuiVu4mM/v9DtUABwQefiK05u9vqtejWfoUzG6TNHxpjYv/pFguDNmPwDHzPhxb4XvwmX82qVDVYQBZhGmAcEIrgJ1XUTfy/f7WPh0OBTi+T995pQS87YSMSXbGTvzooSypac2YA18zCBCo3mSDhMGblvKHfvKAszSYQCEQ/WR3D0jbhxaNKU/nk+hkcbtWQvYvdzZ5dxkEfi7K+CHFGjN7owf1veTl8fCbCPS1MVgJGi5M477u6K4k04SOI9IACOcwpi1vkyTupEypzJyMb+mZG4+VkhZMKSIbeUkG9KWDz+q3VnuD9OW0138iME9AXGulHiB8wr7GgBXoOJIzdF3l11CcZMRYdgG1vIR8BQn6LdgyEz7ueFHVSNSq3Twc0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c\",\"name\":\"connaks-ep8b1c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"91ac6d50-da2c-4621-890a-b4de9a199c98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAqihH1cAkW/NV+Olp8/3fMYPUabrhqX2VLfPbv8FiIS+zBBFm+V85qn4QuFu0pIkMYLxbbOfwb2vEqFHu+x82LS/8YoMkgoDNmywG7wuKeSuKQC627cLL47DLPRsdsD8wI7IkkxVDUF3bczStRKp89YaTQvPT/kHSu7jYH/K7ViwKH34/ftY8iGz7yjpGVglYW6qDZ8x4PcE2uZsmgY/v86G5h8kcidOW3GsGtABw7v1ZTPi4wyYVWFrrvt45ZOQV8TMqz7adCNhDDRfo7xcrSqOp0bvib5l5SHh+4+PNPvcda7aRnZEA/mVqKU5KnlqAUOPaWNi3O9SfeXgt63Y73jbGYcPJREPEJeR1om3JEkJLM2BqbRqntW5+LpJv/l/XKsAnFD5XJEd0QEnN4nKs++huTPorPOBpqRbe5yoKI0m+JUlpGX1C2A+gAJS1GCqY+HkjkxtfZmCiOT8MwVWPOv7iM0NHn7RrFAXWLkKjmHtuNsI/hOR/YcIrz4qBFH8KGohhAESAZiN8GySpsDwYk3XXsKa2FdcPy28Kpyrhn13Nk5y8+AV5fy3/kUsD32PqJbfA3vJh/WiPgviHs2k5XehJlVh8K/vN6aA/sxNXKyFvoN1C9XQ4ZGpxwisJ0tk5DEhnnwmuYOwh1baH9cfUKQkQ/ESK8Fuy/CicBf3ZYv0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}]}" + } + }, + "Get-AzConnectedKubernetes+[NoContext]+Get+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "11" ], + "x-ms-client-request-id": [ "8e65f4b9-18bb-44a5-bb09-45b1ce9ff0cf" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11994" ], + "x-ms-request-id": [ "1f5633e2-51e3-497f-8e39-990a9ef7ae1a" ], + "x-ms-correlation-request-id": [ "1c1925af-022e-43f1-9ef8-1ce204fa4312" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022456Z:1c1925af-022e-43f1-9ef8-1ce204fa4312" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:24:55 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c\",\"name\":\"connaks-s25w9c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"928ddda8-d0c8-4305-bb86-bf23b563de80\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAm/3yDiP5tp78mOXB/vKO6w80pKIEbUfdXsq70i/ssv7N22oMbF+lxOJydclwKrB2jekN+S3lfJd8HfQBnqycsOHEPqVLupN3VGiipKpJekthOeTSRAgFF3t6rc5e9Js/LBg0zfJlVMTni3sV4VU8wS9AGpOIM7CX6ctWgsi/5xkxm3dTpynnuho+s9FdJokkoohWkB1fF/0hMgBBKgtZIKRB343Mkk/2meunnqy5O+E2/IIQf00gf14b7vLKxAY/OdQSgpoD0LIUGNz93K4FQaI33i1GjJWdjPzOtHAI2GZUuiVu4mM/v9DtUABwQefiK05u9vqtejWfoUzG6TNHxpjYv/pFguDNmPwDHzPhxb4XvwmX82qVDVYQBZhGmAcEIrgJ1XUTfy/f7WPh0OBTi+T995pQS87YSMSXbGTvzooSypac2YA18zCBCo3mSDhMGblvKHfvKAszSYQCEQ/WR3D0jbhxaNKU/nk+hkcbtWQvYvdzZ5dxkEfi7K+CHFGjN7owf1veTl8fCbCPS1MVgJGi5M477u6K4k04SOI9IACOcwpi1vkyTupEypzJyMb+mZG4+VkhZMKSIbeUkG9KWDz+q3VnuD9OW0138iME9AXGulHiB8wr7GgBXoOJIzdF3l11CcZMRYdgG1vIR8BQn6LdgyEz7ueFHVSNSq3Twc0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Get-AzConnectedKubernetes+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "12" ], + "x-ms-client-request-id": [ "17b98b55-836d-4094-84c8-e3c3cb8eef6e" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11993" ], + "x-ms-request-id": [ "e0406dec-f4ee-4e93-9ed3-a7f30e04d3e8" ], + "x-ms-correlation-request-id": [ "9e8ff2fe-1ec5-485f-86fc-9618fade510d" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022456Z:9e8ff2fe-1ec5-485f-86fc-9618fade510d" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:24:56 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c\",\"name\":\"connaks-ep8b1c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"91ac6d50-da2c-4621-890a-b4de9a199c98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAqihH1cAkW/NV+Olp8/3fMYPUabrhqX2VLfPbv8FiIS+zBBFm+V85qn4QuFu0pIkMYLxbbOfwb2vEqFHu+x82LS/8YoMkgoDNmywG7wuKeSuKQC627cLL47DLPRsdsD8wI7IkkxVDUF3bczStRKp89YaTQvPT/kHSu7jYH/K7ViwKH34/ftY8iGz7yjpGVglYW6qDZ8x4PcE2uZsmgY/v86G5h8kcidOW3GsGtABw7v1ZTPi4wyYVWFrrvt45ZOQV8TMqz7adCNhDDRfo7xcrSqOp0bvib5l5SHh+4+PNPvcda7aRnZEA/mVqKU5KnlqAUOPaWNi3O9SfeXgt63Y73jbGYcPJREPEJeR1om3JEkJLM2BqbRqntW5+LpJv/l/XKsAnFD5XJEd0QEnN4nKs++huTPorPOBpqRbe5yoKI0m+JUlpGX1C2A+gAJS1GCqY+HkjkxtfZmCiOT8MwVWPOv7iM0NHn7RrFAXWLkKjmHtuNsI/hOR/YcIrz4qBFH8KGohhAESAZiN8GySpsDwYk3XXsKa2FdcPy28Kpyrhn13Nk5y8+AV5fy3/kUsD32PqJbfA3vJh/WiPgviHs2k5XehJlVh8K/vN6aA/sxNXKyFvoN1C9XQ4ZGpxwisJ0tk5DEhnnwmuYOwh1baH9cfUKQkQ/ESK8Fuy/CicBf3ZYv0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Get-AzConnectedKubernetes+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "13" ], + "x-ms-client-request-id": [ "f095472e-4a3c-4f65-81de-86cb51ca8385" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_GetViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11992" ], + "x-ms-request-id": [ "94ec463f-7228-44d0-9ac0-1ba3c23bda55" ], + "x-ms-correlation-request-id": [ "e8c8ae31-2a74-4b22-8975-59667e537aa7" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022457Z:e8c8ae31-2a74-4b22-8975-59667e537aa7" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:24:56 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c\",\"name\":\"connaks-ep8b1c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"91ac6d50-da2c-4621-890a-b4de9a199c98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAqihH1cAkW/NV+Olp8/3fMYPUabrhqX2VLfPbv8FiIS+zBBFm+V85qn4QuFu0pIkMYLxbbOfwb2vEqFHu+x82LS/8YoMkgoDNmywG7wuKeSuKQC627cLL47DLPRsdsD8wI7IkkxVDUF3bczStRKp89YaTQvPT/kHSu7jYH/K7ViwKH34/ftY8iGz7yjpGVglYW6qDZ8x4PcE2uZsmgY/v86G5h8kcidOW3GsGtABw7v1ZTPi4wyYVWFrrvt45ZOQV8TMqz7adCNhDDRfo7xcrSqOp0bvib5l5SHh+4+PNPvcda7aRnZEA/mVqKU5KnlqAUOPaWNi3O9SfeXgt63Y73jbGYcPJREPEJeR1om3JEkJLM2BqbRqntW5+LpJv/l/XKsAnFD5XJEd0QEnN4nKs++huTPorPOBpqRbe5yoKI0m+JUlpGX1C2A+gAJS1GCqY+HkjkxtfZmCiOT8MwVWPOv7iM0NHn7RrFAXWLkKjmHtuNsI/hOR/YcIrz4qBFH8KGohhAESAZiN8GySpsDwYk3XXsKa2FdcPy28Kpyrhn13Nk5y8+AV5fy3/kUsD32PqJbfA3vJh/WiPgviHs2k5XehJlVh8K/vN6aA/sxNXKyFvoN1C9XQ4ZGpxwisJ0tk5DEhnnwmuYOwh1baH9cfUKQkQ/ESK8Fuy/CicBf3ZYv0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/test/Get-AzConnectedKubernetes.Tests.ps1 b/src/ConnectedKubernetes/test/Get-AzConnectedKubernetes.Tests.ps1 new file mode 100644 index 000000000000..b6db69a2a24f --- /dev/null +++ b/src/ConnectedKubernetes/test/Get-AzConnectedKubernetes.Tests.ps1 @@ -0,0 +1,34 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzConnectedKubernetes.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-AzConnectedKubernetes' { + It 'List1' { + $connaksList = Get-AzConnectedKubernetes + $connaksList.Count | Should -BeGreaterOrEqual 2 + } + It 'List' { + $connaksList = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup + $connaksList.Count | Should -BeGreaterOrEqual 2 + } + + It 'Get' { + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName00 + $connaks.Name | Should -Be $env.connaksName00 + } + + It 'GetViaIdentity' { + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName01 + $connaks = Get-AzConnectedKubernetes -InputObject $connaks + $connaks.Name | Should -Be $env.connaksName01 + } +} diff --git a/src/ConnectedKubernetes/test/New-AzConnectedKubernetes.Recording.json b/src/ConnectedKubernetes/test/New-AzConnectedKubernetes.Recording.json new file mode 100644 index 000000000000..b631bdffe0c4 --- /dev/null +++ b/src/ConnectedKubernetes/test/New-AzConnectedKubernetes.Recording.json @@ -0,0 +1,344 @@ +{ + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": "{\n \"location\": \"eastus\",\n \"identity\": {\n \"type\": \"SystemAssigned\"\n },\n \"properties\": {\n \"aadProfile\": {\n \"clientAppId\": \"\",\n \"serverAppId\": \"\",\n \"tenantId\": \"\"\n },\n \"agentPublicKeyCertificate\": \"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "937" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1197" ], + "Azure-AsyncOperation": [ "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/06c01a15-6ce1-42de-b81e-edde285a37a2?api-version=2020-01-01-preview" ], + "x-ms-request-id": [ "06c01a15-6ce1-42de-b81e-edde285a37a2" ], + "x-ms-correlation-request-id": [ "a3598dbd-c43e-42b8-a8cd-5c772a1376f1" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022539Z:a3598dbd-c43e-42b8-a8cd-5c772a1376f1" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:25:39 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1233" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Accepted\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$GET+https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/06c01a15-6ce1-42de-b81e-edde285a37a2?api-version=2020-01-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/06c01a15-6ce1-42de-b81e-edde285a37a2?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "14", "15" ], + "x-ms-client-request-id": [ "cb86b852-b235-4ec8-84e3-f1aa33591b14", "cb86b852-b235-4ec8-84e3-f1aa33591b14" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes" ], + "FullCommandName": [ "New-AzConnectedKubernetes_CreateExpanded", "New-AzConnectedKubernetes_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-tenant-reads": [ "11996" ], + "x-ms-request-id": [ "6a912c54-e581-4cc8-8908-d66214d52147" ], + "x-ms-correlation-request-id": [ "b31b36c2-668f-442d-8db5-94db079095d4" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022609Z:b31b36c2-668f-442d-8db5-94db079095d4" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:26:09 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "239" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/06c01a15-6ce1-42de-b81e-edde285a37a2\",\"name\":\"06c01a15-6ce1-42de-b81e-edde285a37a2\",\"status\":\"Succeeded\",\"startTime\":\"2020-06-15T02:25:36.656749Z\",\"properties\":null}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "14", "15", "16" ], + "x-ms-client-request-id": [ "cb86b852-b235-4ec8-84e3-f1aa33591b14", "cb86b852-b235-4ec8-84e3-f1aa33591b14", "cb86b852-b235-4ec8-84e3-f1aa33591b14" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes" ], + "FullCommandName": [ "New-AzConnectedKubernetes_CreateExpanded", "New-AzConnectedKubernetes_CreateExpanded", "New-AzConnectedKubernetes_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11991" ], + "x-ms-request-id": [ "6f806a8c-e790-4908-b654-f7ef2f6ad761" ], + "x-ms-correlation-request-id": [ "80f9a3ef-588e-445a-a357-88429755b70d" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022610Z:80f9a3ef-588e-445a-a357-88429755b70d" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:26:09 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "17" ], + "x-ms-client-request-id": [ "01eb5424-78dd-4a31-a23b-d8b78a28935f" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11990" ], + "x-ms-request-id": [ "87b0cc93-4c4b-4dd8-b01f-6c7fdcb2a101" ], + "x-ms-correlation-request-id": [ "127e7cce-4705-4436-bfed-16296e45e4e9" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022610Z:127e7cce-4705-4436-bfed-16296e45e4e9" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:26:10 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "18" ], + "x-ms-client-request-id": [ "93e49ee8-7cc8-4a60-8150-7a2b079f5f7d" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 404, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-failure-cause": [ "gateway" ], + "x-ms-request-id": [ "f239ed6c-a21f-4f39-8089-c34f666bad62" ], + "x-ms-correlation-request-id": [ "f239ed6c-a21f-4f39-8089-c34f666bad62" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022623Z:f239ed6c-a21f-4f39-8089-c34f666bad62" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:26:22 GMT" ] + }, + "ContentHeaders": { + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ], + "Content-Length": [ "242" ] + }, + "Content": "{\"error\":{\"code\":\"ResourceNotFound\",\"message\":\"The Resource \u0027Microsoft.Kubernetes/connectedClusters/connaks-7fwpju\u0027 under resource group \u0027connaks-rg-576v9w\u0027 was not found. For more details please go to https://aka.ms/ARMResourceNotFoundFix\"}}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview+6": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview", + "Content": "{\n \"location\": \"eastus\",\n \"identity\": {\n \"type\": \"SystemAssigned\"\n },\n \"properties\": {\n \"aadProfile\": {\n \"clientAppId\": \"\",\n \"serverAppId\": \"\",\n \"tenantId\": \"\"\n },\n \"agentPublicKeyCertificate\": \"MIICCgKCAgEA4ToCaTfWTyM68YKzhS/huf84zt/j4NfvofuZV4miCSrhl4FZ/SEDjz7Hxw+hoHy0cEU9KXrh4jMBk7T0OvLtfqCWfKq1Y5a3BVJO9LcIgSpoaElkz1wj/PvZOToo7I5mPjxAct0dAPEPS3Efa8/UAPik+zX5seWZgIDWG6NPRvNZDQHOCEPsLhe4NtLn7oXzV/r7hHSaiy6TOOfbtZH7L6dbdPBXmGw871neux4TpskqWfl4/wXEzTe+zOkeu8DxjPMMwiOPKWOY8cHstYNlPTzG8jlMyjbL9P2EWPbJvo+RVPQWof85jmr4zwyw5L5t/BIdsKsdWdDa9SliZNpxgo6f4/4lhgXz6/ECvNCl/Asel6c48+Jgw+DHdG2LDcQI7yUBzh5Lnu6vHCERjXUfv0mSG59jC9fAQXfb4ypGI/rB/yuK+x2m/lhEHDamhqVSP49HWWY4WhiOwTihTJ6GLVySfzPLL2G6/CjJMg+PWO5/Kl4zuVYXZeqE198L8+Nz2VoRp88Qlt+r9fb8OvpMIwQqhFN/xPbIqn+/lKC372eYK1PAtk2/rELFttI/QYQHLaJqtpFp2sZ2Co9phpJ88FIAAJK4NgkzFLjre1/pwSwESlCvhIreP7b3gmOxNJaEKiV0oVItyz5UXh2nDaQW5tz2or/SsCRYEVHeNFsWQrsCAwEAAQ==\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "937" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1196" ], + "Azure-AsyncOperation": [ "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/43ed9420-5861-4519-bd0c-8d2df1996034?api-version=2020-01-01-preview" ], + "x-ms-request-id": [ "43ed9420-5861-4519-bd0c-8d2df1996034" ], + "x-ms-correlation-request-id": [ "b301cb93-4ed6-4626-9eee-434bf6c639c5" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022755Z:b301cb93-4ed6-4626-9eee-434bf6c639c5" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:27:54 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1233" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju\",\"name\":\"connaks-7fwpju\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"5c97eb77-0602-4c41-9736-70b0cf91ff6a\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Accepted\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA4ToCaTfWTyM68YKzhS/huf84zt/j4NfvofuZV4miCSrhl4FZ/SEDjz7Hxw+hoHy0cEU9KXrh4jMBk7T0OvLtfqCWfKq1Y5a3BVJO9LcIgSpoaElkz1wj/PvZOToo7I5mPjxAct0dAPEPS3Efa8/UAPik+zX5seWZgIDWG6NPRvNZDQHOCEPsLhe4NtLn7oXzV/r7hHSaiy6TOOfbtZH7L6dbdPBXmGw871neux4TpskqWfl4/wXEzTe+zOkeu8DxjPMMwiOPKWOY8cHstYNlPTzG8jlMyjbL9P2EWPbJvo+RVPQWof85jmr4zwyw5L5t/BIdsKsdWdDa9SliZNpxgo6f4/4lhgXz6/ECvNCl/Asel6c48+Jgw+DHdG2LDcQI7yUBzh5Lnu6vHCERjXUfv0mSG59jC9fAQXfb4ypGI/rB/yuK+x2m/lhEHDamhqVSP49HWWY4WhiOwTihTJ6GLVySfzPLL2G6/CjJMg+PWO5/Kl4zuVYXZeqE198L8+Nz2VoRp88Qlt+r9fb8OvpMIwQqhFN/xPbIqn+/lKC372eYK1PAtk2/rELFttI/QYQHLaJqtpFp2sZ2Co9phpJ88FIAAJK4NgkzFLjre1/pwSwESlCvhIreP7b3gmOxNJaEKiV0oVItyz5UXh2nDaQW5tz2or/SsCRYEVHeNFsWQrsCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$GET+https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/43ed9420-5861-4519-bd0c-8d2df1996034?api-version=2020-01-01-preview+7": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/43ed9420-5861-4519-bd0c-8d2df1996034?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20" ], + "x-ms-client-request-id": [ "45de1754-ce97-4b50-91a6-f398e49d2233", "45de1754-ce97-4b50-91a6-f398e49d2233" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes" ], + "FullCommandName": [ "New-AzConnectedKubernetes_CreateExpanded", "New-AzConnectedKubernetes_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-tenant-reads": [ "11995" ], + "x-ms-request-id": [ "2ac678e1-e232-46b4-bcd7-4c9f75e441da" ], + "x-ms-correlation-request-id": [ "9ff09210-fd08-4d07-a4d4-900dbd1b0a42" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022825Z:9ff09210-fd08-4d07-a4d4-900dbd1b0a42" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:28:25 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "240" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/43ed9420-5861-4519-bd0c-8d2df1996034\",\"name\":\"43ed9420-5861-4519-bd0c-8d2df1996034\",\"status\":\"Succeeded\",\"startTime\":\"2020-06-15T02:27:51.8289162Z\",\"properties\":null}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview+8": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21" ], + "x-ms-client-request-id": [ "45de1754-ce97-4b50-91a6-f398e49d2233", "45de1754-ce97-4b50-91a6-f398e49d2233", "45de1754-ce97-4b50-91a6-f398e49d2233" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\New-AzConnectedKubernetes" ], + "FullCommandName": [ "New-AzConnectedKubernetes_CreateExpanded", "New-AzConnectedKubernetes_CreateExpanded", "New-AzConnectedKubernetes_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11988" ], + "x-ms-request-id": [ "80420f9a-6e74-4399-b7b5-a8290c27a852" ], + "x-ms-correlation-request-id": [ "00780037-1c6a-4ab2-9ab3-e84ff6ad8e5e" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022826Z:00780037-1c6a-4ab2-9ab3-e84ff6ad8e5e" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:28:25 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju\",\"name\":\"connaks-7fwpju\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"5c97eb77-0602-4c41-9736-70b0cf91ff6a\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA4ToCaTfWTyM68YKzhS/huf84zt/j4NfvofuZV4miCSrhl4FZ/SEDjz7Hxw+hoHy0cEU9KXrh4jMBk7T0OvLtfqCWfKq1Y5a3BVJO9LcIgSpoaElkz1wj/PvZOToo7I5mPjxAct0dAPEPS3Efa8/UAPik+zX5seWZgIDWG6NPRvNZDQHOCEPsLhe4NtLn7oXzV/r7hHSaiy6TOOfbtZH7L6dbdPBXmGw871neux4TpskqWfl4/wXEzTe+zOkeu8DxjPMMwiOPKWOY8cHstYNlPTzG8jlMyjbL9P2EWPbJvo+RVPQWof85jmr4zwyw5L5t/BIdsKsdWdDa9SliZNpxgo6f4/4lhgXz6/ECvNCl/Asel6c48+Jgw+DHdG2LDcQI7yUBzh5Lnu6vHCERjXUfv0mSG59jC9fAQXfb4ypGI/rB/yuK+x2m/lhEHDamhqVSP49HWWY4WhiOwTihTJ6GLVySfzPLL2G6/CjJMg+PWO5/Kl4zuVYXZeqE198L8+Nz2VoRp88Qlt+r9fb8OvpMIwQqhFN/xPbIqn+/lKC372eYK1PAtk2/rELFttI/QYQHLaJqtpFp2sZ2Co9phpJ88FIAAJK4NgkzFLjre1/pwSwESlCvhIreP7b3gmOxNJaEKiV0oVItyz5UXh2nDaQW5tz2or/SsCRYEVHeNFsWQrsCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "New-AzConnectedKubernetes+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview+9": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "22" ], + "x-ms-client-request-id": [ "1a58b0e5-b273-4957-b505-7b4e84938bf3" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11987" ], + "x-ms-request-id": [ "081bbda4-e1fd-47ed-9f0b-a89d25a78215" ], + "x-ms-correlation-request-id": [ "e723a943-7871-4016-be05-fc2648bf39b7" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022826Z:e723a943-7871-4016-be05-fc2648bf39b7" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:28:26 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju\",\"name\":\"connaks-7fwpju\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"5c97eb77-0602-4c41-9736-70b0cf91ff6a\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA4ToCaTfWTyM68YKzhS/huf84zt/j4NfvofuZV4miCSrhl4FZ/SEDjz7Hxw+hoHy0cEU9KXrh4jMBk7T0OvLtfqCWfKq1Y5a3BVJO9LcIgSpoaElkz1wj/PvZOToo7I5mPjxAct0dAPEPS3Efa8/UAPik+zX5seWZgIDWG6NPRvNZDQHOCEPsLhe4NtLn7oXzV/r7hHSaiy6TOOfbtZH7L6dbdPBXmGw871neux4TpskqWfl4/wXEzTe+zOkeu8DxjPMMwiOPKWOY8cHstYNlPTzG8jlMyjbL9P2EWPbJvo+RVPQWof85jmr4zwyw5L5t/BIdsKsdWdDa9SliZNpxgo6f4/4lhgXz6/ECvNCl/Asel6c48+Jgw+DHdG2LDcQI7yUBzh5Lnu6vHCERjXUfv0mSG59jC9fAQXfb4ypGI/rB/yuK+x2m/lhEHDamhqVSP49HWWY4WhiOwTihTJ6GLVySfzPLL2G6/CjJMg+PWO5/Kl4zuVYXZeqE198L8+Nz2VoRp88Qlt+r9fb8OvpMIwQqhFN/xPbIqn+/lKC372eYK1PAtk2/rELFttI/QYQHLaJqtpFp2sZ2Co9phpJ88FIAAJK4NgkzFLjre1/pwSwESlCvhIreP7b3gmOxNJaEKiV0oVItyz5UXh2nDaQW5tz2or/SsCRYEVHeNFsWQrsCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/test/New-AzConnectedKubernetes.Tests.ps1 b/src/ConnectedKubernetes/test/New-AzConnectedKubernetes.Tests.ps1 new file mode 100644 index 000000000000..af02c4bbd7ec --- /dev/null +++ b/src/ConnectedKubernetes/test/New-AzConnectedKubernetes.Tests.ps1 @@ -0,0 +1,27 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzConnectedKubernetes.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzConnectedKubernetes' { + # The cmdlet does not support the playback model because it uses helm and kubectl + It 'CreateExpanded' -skip { + New-AzConnectedKubernetes -ClusterName $env.connaksName02 -ResourceGroupName $env.resourceGroup -Location $env.location -KubeConfig $HOME\.kube\config -KubeContext $env.kubeContext + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName02 + $connaks.ProvisioningState | Should -Be 'Succeeded' + + New-AzConnectedKubernetes -ClusterName $env.connaksName03 -ResourceGroupName $env.resourceGroup -Location $env.location + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName03 + $connaks.ProvisioningState | Should -Be 'Succeeded' + # Clear helm azure-arc environment + helm delete azure-arc --no-hooks + } +} diff --git a/src/ConnectedKubernetes/test/Remove-AzConnectedKubernetes.Recording.json b/src/ConnectedKubernetes/test/Remove-AzConnectedKubernetes.Recording.json new file mode 100644 index 000000000000..0acfdd8da57c --- /dev/null +++ b/src/ConnectedKubernetes/test/Remove-AzConnectedKubernetes.Recording.json @@ -0,0 +1,355 @@ +{ + "Remove-AzConnectedKubernetes+[NoContext]+Delete+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "23" ], + "x-ms-client-request-id": [ "5dff8eaa-29b6-4be1-97b8-8dbf2288226b" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes" ], + "FullCommandName": [ "Remove-AzConnectedKubernetes_Delete" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/9cd00bb7-d95a-448f-bae2-324dc90a016c?api-version=2020-01-01-preview" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14999" ], + "x-ms-request-id": [ "9cd00bb7-d95a-448f-bae2-324dc90a016c" ], + "x-ms-correlation-request-id": [ "87562104-cc64-458e-b00e-0fe9941aac56" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022904Z:87562104-cc64-458e-b00e-0fe9941aac56" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:29:04 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1233" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-s25w9c\",\"name\":\"connaks-s25w9c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"928ddda8-d0c8-4305-bb86-bf23b563de80\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Deleting\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAm/3yDiP5tp78mOXB/vKO6w80pKIEbUfdXsq70i/ssv7N22oMbF+lxOJydclwKrB2jekN+S3lfJd8HfQBnqycsOHEPqVLupN3VGiipKpJekthOeTSRAgFF3t6rc5e9Js/LBg0zfJlVMTni3sV4VU8wS9AGpOIM7CX6ctWgsi/5xkxm3dTpynnuho+s9FdJokkoohWkB1fF/0hMgBBKgtZIKRB343Mkk/2meunnqy5O+E2/IIQf00gf14b7vLKxAY/OdQSgpoD0LIUGNz93K4FQaI33i1GjJWdjPzOtHAI2GZUuiVu4mM/v9DtUABwQefiK05u9vqtejWfoUzG6TNHxpjYv/pFguDNmPwDHzPhxb4XvwmX82qVDVYQBZhGmAcEIrgJ1XUTfy/f7WPh0OBTi+T995pQS87YSMSXbGTvzooSypac2YA18zCBCo3mSDhMGblvKHfvKAszSYQCEQ/WR3D0jbhxaNKU/nk+hkcbtWQvYvdzZ5dxkEfi7K+CHFGjN7owf1veTl8fCbCPS1MVgJGi5M477u6K4k04SOI9IACOcwpi1vkyTupEypzJyMb+mZG4+VkhZMKSIbeUkG9KWDz+q3VnuD9OW0138iME9AXGulHiB8wr7GgBXoOJIzdF3l11CcZMRYdgG1vIR8BQn6LdgyEz7ueFHVSNSq3Twc0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+Delete+$GET+https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/9cd00bb7-d95a-448f-bae2-324dc90a016c?api-version=2020-01-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/9cd00bb7-d95a-448f-bae2-324dc90a016c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "23", "24" ], + "x-ms-client-request-id": [ "5dff8eaa-29b6-4be1-97b8-8dbf2288226b", "5dff8eaa-29b6-4be1-97b8-8dbf2288226b" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes" ], + "FullCommandName": [ "Remove-AzConnectedKubernetes_Delete", "Remove-AzConnectedKubernetes_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-tenant-reads": [ "11994" ], + "x-ms-request-id": [ "fae2664d-34cc-4795-959f-2224116afb9b" ], + "x-ms-correlation-request-id": [ "4390033b-d539-4515-bf29-f6ea36d838ad" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022935Z:4390033b-d539-4515-bf29-f6ea36d838ad" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:29:35 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "240" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/9cd00bb7-d95a-448f-bae2-324dc90a016c\",\"name\":\"9cd00bb7-d95a-448f-bae2-324dc90a016c\",\"status\":\"Succeeded\",\"startTime\":\"2020-06-15T02:29:04.1077217Z\",\"properties\":null}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+Delete+$GET+https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/9cd00bb7-d95a-448f-bae2-324dc90a016c?api-version=2020-01-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/9cd00bb7-d95a-448f-bae2-324dc90a016c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "23", "24", "25" ], + "x-ms-client-request-id": [ "5dff8eaa-29b6-4be1-97b8-8dbf2288226b", "5dff8eaa-29b6-4be1-97b8-8dbf2288226b", "5dff8eaa-29b6-4be1-97b8-8dbf2288226b" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes" ], + "FullCommandName": [ "Remove-AzConnectedKubernetes_Delete", "Remove-AzConnectedKubernetes_Delete", "Remove-AzConnectedKubernetes_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-tenant-reads": [ "11993" ], + "x-ms-request-id": [ "dfb57d6d-f5b3-48a2-9876-e65c19ed3269" ], + "x-ms-correlation-request-id": [ "b3c6c301-8064-461b-9fc7-d1e6250723b6" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022935Z:b3c6c301-8064-461b-9fc7-d1e6250723b6" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:29:35 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "240" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/9cd00bb7-d95a-448f-bae2-324dc90a016c\",\"name\":\"9cd00bb7-d95a-448f-bae2-324dc90a016c\",\"status\":\"Succeeded\",\"startTime\":\"2020-06-15T02:29:04.1077217Z\",\"properties\":null}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "26" ], + "x-ms-client-request-id": [ "c276e343-53d8-434a-a9b6-12619915efb8" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11986" ], + "x-ms-request-id": [ "a1358da2-ccb8-4548-936e-4451637fb060" ], + "x-ms-correlation-request-id": [ "64eddf92-db27-4f6c-8770-fea9643c563c" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022936Z:64eddf92-db27-4f6c-8770-fea9643c563c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:29:35 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "3716" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c\",\"name\":\"connaks-ep8b1c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"91ac6d50-da2c-4621-890a-b4de9a199c98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAqihH1cAkW/NV+Olp8/3fMYPUabrhqX2VLfPbv8FiIS+zBBFm+V85qn4QuFu0pIkMYLxbbOfwb2vEqFHu+x82LS/8YoMkgoDNmywG7wuKeSuKQC627cLL47DLPRsdsD8wI7IkkxVDUF3bczStRKp89YaTQvPT/kHSu7jYH/K7ViwKH34/ftY8iGz7yjpGVglYW6qDZ8x4PcE2uZsmgY/v86G5h8kcidOW3GsGtABw7v1ZTPi4wyYVWFrrvt45ZOQV8TMqz7adCNhDDRfo7xcrSqOp0bvib5l5SHh+4+PNPvcda7aRnZEA/mVqKU5KnlqAUOPaWNi3O9SfeXgt63Y73jbGYcPJREPEJeR1om3JEkJLM2BqbRqntW5+LpJv/l/XKsAnFD5XJEd0QEnN4nKs++huTPorPOBpqRbe5yoKI0m+JUlpGX1C2A+gAJS1GCqY+HkjkxtfZmCiOT8MwVWPOv7iM0NHn7RrFAXWLkKjmHtuNsI/hOR/YcIrz4qBFH8KGohhAESAZiN8GySpsDwYk3XXsKa2FdcPy28Kpyrhn13Nk5y8+AV5fy3/kUsD32PqJbfA3vJh/WiPgviHs2k5XehJlVh8K/vN6aA/sxNXKyFvoN1C9XQ4ZGpxwisJ0tk5DEhnnwmuYOwh1baH9cfUKQkQ/ESK8Fuy/CicBf3ZYv0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju\",\"name\":\"connaks-7fwpju\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"5c97eb77-0602-4c41-9736-70b0cf91ff6a\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA4ToCaTfWTyM68YKzhS/huf84zt/j4NfvofuZV4miCSrhl4FZ/SEDjz7Hxw+hoHy0cEU9KXrh4jMBk7T0OvLtfqCWfKq1Y5a3BVJO9LcIgSpoaElkz1wj/PvZOToo7I5mPjxAct0dAPEPS3Efa8/UAPik+zX5seWZgIDWG6NPRvNZDQHOCEPsLhe4NtLn7oXzV/r7hHSaiy6TOOfbtZH7L6dbdPBXmGw871neux4TpskqWfl4/wXEzTe+zOkeu8DxjPMMwiOPKWOY8cHstYNlPTzG8jlMyjbL9P2EWPbJvo+RVPQWof85jmr4zwyw5L5t/BIdsKsdWdDa9SliZNpxgo6f4/4lhgXz6/ECvNCl/Asel6c48+Jgw+DHdG2LDcQI7yUBzh5Lnu6vHCERjXUfv0mSG59jC9fAQXfb4ypGI/rB/yuK+x2m/lhEHDamhqVSP49HWWY4WhiOwTihTJ6GLVySfzPLL2G6/CjJMg+PWO5/Kl4zuVYXZeqE198L8+Nz2VoRp88Qlt+r9fb8OvpMIwQqhFN/xPbIqn+/lKC372eYK1PAtk2/rELFttI/QYQHLaJqtpFp2sZ2Co9phpJ88FIAAJK4NgkzFLjre1/pwSwESlCvhIreP7b3gmOxNJaEKiV0oVItyz5UXh2nDaQW5tz2or/SsCRYEVHeNFsWQrsCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}]}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "27" ], + "x-ms-client-request-id": [ "e7971c1c-8e2a-4882-abf1-2de7dd39a696" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11985" ], + "x-ms-request-id": [ "eba63d34-2714-44df-9172-07a6c990bba8" ], + "x-ms-correlation-request-id": [ "223f3b35-31da-4e8f-a6cf-d9c10ed6e325" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022937Z:223f3b35-31da-4e8f-a6cf-d9c10ed6e325" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:29:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1234" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c\",\"name\":\"connaks-ep8b1c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"91ac6d50-da2c-4621-890a-b4de9a199c98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAqihH1cAkW/NV+Olp8/3fMYPUabrhqX2VLfPbv8FiIS+zBBFm+V85qn4QuFu0pIkMYLxbbOfwb2vEqFHu+x82LS/8YoMkgoDNmywG7wuKeSuKQC627cLL47DLPRsdsD8wI7IkkxVDUF3bczStRKp89YaTQvPT/kHSu7jYH/K7ViwKH34/ftY8iGz7yjpGVglYW6qDZ8x4PcE2uZsmgY/v86G5h8kcidOW3GsGtABw7v1ZTPi4wyYVWFrrvt45ZOQV8TMqz7adCNhDDRfo7xcrSqOp0bvib5l5SHh+4+PNPvcda7aRnZEA/mVqKU5KnlqAUOPaWNi3O9SfeXgt63Y73jbGYcPJREPEJeR1om3JEkJLM2BqbRqntW5+LpJv/l/XKsAnFD5XJEd0QEnN4nKs++huTPorPOBpqRbe5yoKI0m+JUlpGX1C2A+gAJS1GCqY+HkjkxtfZmCiOT8MwVWPOv7iM0NHn7RrFAXWLkKjmHtuNsI/hOR/YcIrz4qBFH8KGohhAESAZiN8GySpsDwYk3XXsKa2FdcPy28Kpyrhn13Nk5y8+AV5fy3/kUsD32PqJbfA3vJh/WiPgviHs2k5XehJlVh8K/vN6aA/sxNXKyFvoN1C9XQ4ZGpxwisJ0tk5DEhnnwmuYOwh1baH9cfUKQkQ/ESK8Fuy/CicBf3ZYv0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+DeleteViaIdentity+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview+2": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "28" ], + "x-ms-client-request-id": [ "985dd9a6-c2f3-40ad-a754-3ebe2bf33f71" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes" ], + "FullCommandName": [ "Remove-AzConnectedKubernetes_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/56614cd0-dbb0-4e0e-9734-f5ea559c2252?api-version=2020-01-01-preview" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14998" ], + "x-ms-request-id": [ "56614cd0-dbb0-4e0e-9734-f5ea559c2252" ], + "x-ms-correlation-request-id": [ "051736f1-eb82-4111-8bb5-23410d3d57c0" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T022950Z:051736f1-eb82-4111-8bb5-23410d3d57c0" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:29:50 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1233" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-ep8b1c\",\"name\":\"connaks-ep8b1c\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"91ac6d50-da2c-4621-890a-b4de9a199c98\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Deleting\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAqihH1cAkW/NV+Olp8/3fMYPUabrhqX2VLfPbv8FiIS+zBBFm+V85qn4QuFu0pIkMYLxbbOfwb2vEqFHu+x82LS/8YoMkgoDNmywG7wuKeSuKQC627cLL47DLPRsdsD8wI7IkkxVDUF3bczStRKp89YaTQvPT/kHSu7jYH/K7ViwKH34/ftY8iGz7yjpGVglYW6qDZ8x4PcE2uZsmgY/v86G5h8kcidOW3GsGtABw7v1ZTPi4wyYVWFrrvt45ZOQV8TMqz7adCNhDDRfo7xcrSqOp0bvib5l5SHh+4+PNPvcda7aRnZEA/mVqKU5KnlqAUOPaWNi3O9SfeXgt63Y73jbGYcPJREPEJeR1om3JEkJLM2BqbRqntW5+LpJv/l/XKsAnFD5XJEd0QEnN4nKs++huTPorPOBpqRbe5yoKI0m+JUlpGX1C2A+gAJS1GCqY+HkjkxtfZmCiOT8MwVWPOv7iM0NHn7RrFAXWLkKjmHtuNsI/hOR/YcIrz4qBFH8KGohhAESAZiN8GySpsDwYk3XXsKa2FdcPy28Kpyrhn13Nk5y8+AV5fy3/kUsD32PqJbfA3vJh/WiPgviHs2k5XehJlVh8K/vN6aA/sxNXKyFvoN1C9XQ4ZGpxwisJ0tk5DEhnnwmuYOwh1baH9cfUKQkQ/ESK8Fuy/CicBf3ZYv0CAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/56614cd0-dbb0-4e0e-9734-f5ea559c2252?api-version=2020-01-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/56614cd0-dbb0-4e0e-9734-f5ea559c2252?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "28", "29" ], + "x-ms-client-request-id": [ "985dd9a6-c2f3-40ad-a754-3ebe2bf33f71", "985dd9a6-c2f3-40ad-a754-3ebe2bf33f71" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes" ], + "FullCommandName": [ "Remove-AzConnectedKubernetes_DeleteViaIdentity", "Remove-AzConnectedKubernetes_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-tenant-reads": [ "11992" ], + "x-ms-request-id": [ "042988d8-a68e-470d-b219-c37f5961ec98" ], + "x-ms-correlation-request-id": [ "68168dbf-2671-4011-8ef2-a197037129db" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023021Z:68168dbf-2671-4011-8ef2-a197037129db" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:20 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "240" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/56614cd0-dbb0-4e0e-9734-f5ea559c2252\",\"name\":\"56614cd0-dbb0-4e0e-9734-f5ea559c2252\",\"status\":\"Succeeded\",\"startTime\":\"2020-06-15T02:29:49.9006076Z\",\"properties\":null}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/56614cd0-dbb0-4e0e-9734-f5ea559c2252?api-version=2020-01-01-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/56614cd0-dbb0-4e0e-9734-f5ea559c2252?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "28", "29", "30" ], + "x-ms-client-request-id": [ "985dd9a6-c2f3-40ad-a754-3ebe2bf33f71", "985dd9a6-c2f3-40ad-a754-3ebe2bf33f71", "985dd9a6-c2f3-40ad-a754-3ebe2bf33f71" ], + "CommandName": [ "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes", "Az.ConnectedKubernetes.internal\\Remove-AzConnectedKubernetes" ], + "FullCommandName": [ "Remove-AzConnectedKubernetes_DeleteViaIdentity", "Remove-AzConnectedKubernetes_DeleteViaIdentity", "Remove-AzConnectedKubernetes_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-tenant-reads": [ "11991" ], + "x-ms-request-id": [ "4e11129b-0666-48eb-b33a-f726dfff0820" ], + "x-ms-correlation-request-id": [ "2feffa03-fca4-4863-be7e-7ac879e18863" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023021Z:2feffa03-fca4-4863-be7e-7ac879e18863" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:20 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "240" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/providers/Microsoft.Kubernetes/locations/EASTUS/operationStatuses/56614cd0-dbb0-4e0e-9734-f5ea559c2252\",\"name\":\"56614cd0-dbb0-4e0e-9734-f5ea559c2252\",\"status\":\"Succeeded\",\"startTime\":\"2020-06-15T02:29:49.9006076Z\",\"properties\":null}" + } + }, + "Remove-AzConnectedKubernetes+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "31" ], + "x-ms-client-request-id": [ "d0890234-5e9e-4a6a-a8d9-0d2fe590d323" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11984" ], + "x-ms-request-id": [ "66785cf4-37a8-43ec-8968-2ae4fad0ac6f" ], + "x-ms-correlation-request-id": [ "11e6c19f-883e-497d-b69a-673139e96e7f" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023022Z:11e6c19f-883e-497d-b69a-673139e96e7f" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:21 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "2481" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}},{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-7fwpju\",\"name\":\"connaks-7fwpju\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"5c97eb77-0602-4c41-9736-70b0cf91ff6a\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEA4ToCaTfWTyM68YKzhS/huf84zt/j4NfvofuZV4miCSrhl4FZ/SEDjz7Hxw+hoHy0cEU9KXrh4jMBk7T0OvLtfqCWfKq1Y5a3BVJO9LcIgSpoaElkz1wj/PvZOToo7I5mPjxAct0dAPEPS3Efa8/UAPik+zX5seWZgIDWG6NPRvNZDQHOCEPsLhe4NtLn7oXzV/r7hHSaiy6TOOfbtZH7L6dbdPBXmGw871neux4TpskqWfl4/wXEzTe+zOkeu8DxjPMMwiOPKWOY8cHstYNlPTzG8jlMyjbL9P2EWPbJvo+RVPQWof85jmr4zwyw5L5t/BIdsKsdWdDa9SliZNpxgo6f4/4lhgXz6/ECvNCl/Asel6c48+Jgw+DHdG2LDcQI7yUBzh5Lnu6vHCERjXUfv0mSG59jC9fAQXfb4ypGI/rB/yuK+x2m/lhEHDamhqVSP49HWWY4WhiOwTihTJ6GLVySfzPLL2G6/CjJMg+PWO5/Kl4zuVYXZeqE198L8+Nz2VoRp88Qlt+r9fb8OvpMIwQqhFN/xPbIqn+/lKC372eYK1PAtk2/rELFttI/QYQHLaJqtpFp2sZ2Co9phpJ88FIAAJK4NgkzFLjre1/pwSwESlCvhIreP7b3gmOxNJaEKiV0oVItyz5UXh2nDaQW5tz2or/SsCRYEVHeNFsWQrsCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}]}" + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/test/Remove-AzConnectedKubernetes.Tests.ps1 b/src/ConnectedKubernetes/test/Remove-AzConnectedKubernetes.Tests.ps1 new file mode 100644 index 000000000000..540aea155cd5 --- /dev/null +++ b/src/ConnectedKubernetes/test/Remove-AzConnectedKubernetes.Tests.ps1 @@ -0,0 +1,29 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzConnectedKubernetes.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzConnectedKubernetes' { + # The cmdlet does not support the playback model because it uses helm and kubectl + It 'Delete' -skip { + Remove-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName00 + $connaksList = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup + $connaksList.Name | Should -Not -Contain $env.connaksName00 + + } + + It 'DeleteViaIdentity' -skip { + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName01 + Remove-AzConnectedKubernetes -InputObject $connaks + $connaksList = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup + $connaksList.Name | Should -Not -Contain $env.connaksName01 + } +} diff --git a/src/ConnectedKubernetes/test/Update-AzConnectedKubernetes.Recording.json b/src/ConnectedKubernetes/test/Update-AzConnectedKubernetes.Recording.json new file mode 100644 index 000000000000..5aec88abd8ff --- /dev/null +++ b/src/ConnectedKubernetes/test/Update-AzConnectedKubernetes.Recording.json @@ -0,0 +1,187 @@ +{ + "Update-AzConnectedKubernetes+[NoContext]+UpdateExpanded+$PATCH+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "PATCH", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": "{\n \"tags\": {\n \"key2\": \"2\",\n \"key1\": \"1\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "52" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1195" ], + "x-ms-request-id": [ "67eff90a-ec7a-4cc2-8d57-3473c952cbbd" ], + "x-ms-correlation-request-id": [ "0e541615-9aac-417c-b57b-a5f08d5a4219" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023028Z:0e541615-9aac-417c-b57b-a5f08d5a4219" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:27 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1265" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key2\":\"2\",\"key1\":\"1\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Update-AzConnectedKubernetes+[NoContext]+UpdateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "33" ], + "x-ms-client-request-id": [ "d75273b2-e209-4b98-be78-0505515208c5" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11983" ], + "x-ms-request-id": [ "08dd5b32-46f9-412c-9edd-5f2562680fb4" ], + "x-ms-correlation-request-id": [ "4dcc53d5-8a6b-4f01-972c-efef7181131c" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023028Z:4dcc53d5-8a6b-4f01-972c-efef7181131c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:28 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1265" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key2\":\"2\",\"key1\":\"1\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Update-AzConnectedKubernetes+[NoContext]+UpdateViaIdentityExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "34" ], + "x-ms-client-request-id": [ "8f6ef71a-473b-4d1b-810b-a5b5d7e46d61" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11982" ], + "x-ms-request-id": [ "64439cc2-030e-4e95-8a56-204f7b7fae37" ], + "x-ms-correlation-request-id": [ "11157ba1-149c-4e9e-a205-9752e833267f" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023029Z:11157ba1-149c-4e9e-a205-9752e833267f" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:28 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1265" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key2\":\"2\",\"key1\":\"1\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Update-AzConnectedKubernetes+[NoContext]+UpdateViaIdentityExpanded+$PATCH+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+2": { + "Request": { + "Method": "PATCH", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": "{\n \"tags\": {\n \"key2\": \"2\",\n \"key1\": \"1\",\n \"key3\": \"3\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "69" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1194" ], + "x-ms-request-id": [ "aa3ae2a6-0ffd-4302-98e0-f7113da88c01" ], + "x-ms-correlation-request-id": [ "e2f430e8-b619-4801-bb4b-1d94f5149b8b" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023033Z:e2f430e8-b619-4801-bb4b-1d94f5149b8b" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:32 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1276" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key2\":\"2\",\"key1\":\"1\",\"key3\":\"3\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + }, + "Update-AzConnectedKubernetes+[NoContext]+UpdateViaIdentityExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb?api-version=2020-01-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "36" ], + "x-ms-client-request-id": [ "db0ce91f-1780-4150-9f9f-5616637f17ce" ], + "CommandName": [ "Get-AzConnectedKubernetes" ], + "FullCommandName": [ "Get-AzConnectedKubernetes_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11981" ], + "x-ms-request-id": [ "5a61fd44-7494-48b2-a618-59fa538984e6" ], + "x-ms-correlation-request-id": [ "d1163bd2-6f2f-47c0-8bed-b1b81ddcca52" ], + "Server": [ "Kestrel" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200615T023033Z:d1163bd2-6f2f-47c0-8bed-b1b81ddcca52" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 15 Jun 2020 02:30:32 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1276" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-576v9w/providers/Microsoft.Kubernetes/connectedClusters/connaks-deq5jb\",\"name\":\"connaks-deq5jb\",\"type\":\"Microsoft.Kubernetes/connectedClusters\",\"location\":\"eastus\",\"tags\":{\"key2\":\"2\",\"key1\":\"1\",\"key3\":\"3\"},\"identity\":{\"type\":\"SystemAssigned\",\"principalId\":\"d5cd956f-02f6-438e-bbd2-0fbf2345f0fb\",\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\"},\"properties\":{\"provisioningState\":\"Succeeded\",\"agentPublicKeyCertificate\":\"MIICCgKCAgEAt6pHqmxsKsyoArEOEip33Ur3jKAvN53nOWB1Kjoxd/PnZCxaaesZIvdqEuX0K5AVdc+rTjrZE8ibLSEkzNtsjL4wncw8o0ze2sJ487eNrVebzJx3By3XEpTuGEbgDazvECrJtZxUZpiBKsQRFNuTArRF5dkFIyhHFKBbOTTyEjkXaFlI2Zyv3057jAnJL6txpJhxIu/lL2XDJCtVsQF8owpdVedAYroM1UxA6zcLOReHRdXfbbnChWBmog90Mgeyu1acWITGYnoAVi5vOts0P0kBF//YKVPXYqShegmWWzCwOQRWAg3KMkLrVUt66jUnYLpnhhHokdogbDcSNuT1KBCj16YGKWCcgXbWKBYR8sD2dYlIoAZsCnVScXTT5b65bRZBhW69p0jPjt4IgoArjB43hJb/kwEMh+GFE9ZSiS92qOyAWQ5WNEYimUH8lu3pvYIDoPZ2/eX6kz4Dv+pBPp251r5VJBRBvn3apLZ08QfgxjAnTgIJGOAt4Sz6g3ikmvdPHUPbPgEYymPBrxBIML8kOqL5LUeuMAA4i8B10NPU5AM7A0WJZX3TuQOyj5YNhhvztdVbAnbhPwSO1V3y6h9uv7ks27Krp7sLuLMIDangVb61hFkzI7Vm8WCgpSxrWVLSdx5z9dhtMoPdp5NZILUSiLsIuGfq9NpEGWgIZBUCAwEAAQ==\",\"aadProfile\":{\"tenantId\":\"\",\"clientAppId\":\"\",\"serverAppId\":\"\"}}}" + } + } +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/test/Update-AzConnectedKubernetes.Tests.ps1 b/src/ConnectedKubernetes/test/Update-AzConnectedKubernetes.Tests.ps1 new file mode 100644 index 000000000000..ce8df95bb399 --- /dev/null +++ b/src/ConnectedKubernetes/test/Update-AzConnectedKubernetes.Tests.ps1 @@ -0,0 +1,27 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Update-AzConnectedKubernetes.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 'Update-AzConnectedKubernetes' { + It 'UpdateExpanded' { + Update-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName02 -Tag @{'key1'= 1; 'key2'= 2} + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName02 + $connaks.Tag.Count | Should -Be 2 + } + + It 'UpdateViaIdentityExpanded' { + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName02 + Update-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName02 -Tag @{'key1'= 1; 'key2'= 2; 'key3'= 3} + $connaks = Get-AzConnectedKubernetes -ResourceGroupName $env.resourceGroup -Name $env.connaksName02 + $connaks.Tag.Count | Should -Be 3 + } +} diff --git a/src/ConnectedKubernetes/test/env.json b/src/ConnectedKubernetes/test/env.json new file mode 100644 index 000000000000..3c88dc4b345c --- /dev/null +++ b/src/ConnectedKubernetes/test/env.json @@ -0,0 +1,11 @@ +{ + "connaksName03": "connaks-7fwpju", + "SubscriptionId": "9e223dbe-3399-4e19-88eb-0975f02ac87f", + "resourceGroup": "connaks-rg-576v9w", + "connaksName01": "connaks-ep8b1c", + "kubeContext": "portal-aks-t01", + "location": "eastus", + "connaksName02": "connaks-deq5jb", + "Tenant": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "connaksName00": "connaks-s25w9c" +} diff --git a/src/ConnectedKubernetes/test/loadEnv.ps1 b/src/ConnectedKubernetes/test/loadEnv.ps1 new file mode 100644 index 000000000000..c4ebf2e8310c --- /dev/null +++ b/src/ConnectedKubernetes/test/loadEnv.ps1 @@ -0,0 +1,28 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:SubscriptionId"=$env.SubscriptionId; "*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/src/ConnectedKubernetes/test/readme.md b/src/ConnectedKubernetes/test/readme.md new file mode 100644 index 000000000000..1969200c6a09 --- /dev/null +++ b/src/ConnectedKubernetes/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/ConnectedKubernetes/test/utils.ps1 b/src/ConnectedKubernetes/test/utils.ps1 new file mode 100644 index 000000000000..d97a8f940e67 --- /dev/null +++ b/src/ConnectedKubernetes/test/utils.ps1 @@ -0,0 +1,44 @@ +function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + Write-Host -ForegroundColor Yellow "WARNING: Expected that the user has kubeconfig and cluster-admin access as well helm3 installed, please check if installed Helm3 and Kubectl." + $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. + $env.resourceGroup = 'connaks-rg-' + (RandomString -allChars $false -len 6) + $env.location = 'eastus' + New-AzResourceGroup -Name $env.resourceGroup -Location $env.Location + + $connaksName00 = 'connaks-' + (RandomString -allChars $false -len 6) + $connaksName01 = 'connaks-' + (RandomString -allChars $false -len 6) + $connaksName02 = 'connaks-' + (RandomString -allChars $false -len 6) + $connaksName03 = 'connaks-' + (RandomString -allChars $false -len 6) + $env.Add('connaksName00', $connaksName00) + $env.Add('connaksName01', $connaksName01) + $env.Add('connaksName02', $connaksName02) + $env.Add('connaksName03', $connaksName03) + + $kubeContext = 'portal-aks-t01' + $env.Add('kubeContext', $kubeContext) + New-AzConnectedKubernetes -ClusterName $env.connaksName00 -ResourceGroupName $env.resourceGroup -Location $env.location + New-AzConnectedKubernetes -ClusterName $env.connaksName01 -ResourceGroupName $env.resourceGroup -Location $env.location -KubeConfig $HOME\.kube\config -KubeContext $kubeContext + + $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 + Remove-AzResourceGroup -Name $env.ResourceGroup +} + diff --git a/src/CustomProviders/Az.CustomProviders.csproj b/src/CustomProviders/Az.CustomProviders.csproj new file mode 100644 index 000000000000..a4c0a69aa7e3 --- /dev/null +++ b/src/CustomProviders/Az.CustomProviders.csproj @@ -0,0 +1,7 @@ + + + CustomProviders + + + + \ No newline at end of file diff --git a/src/CustomProviders/Az.CustomProviders.format.ps1xml b/src/CustomProviders/Az.CustomProviders.format.ps1xml new file mode 100644 index 000000000000..41166bdb00f8 --- /dev/null +++ b/src/CustomProviders/Az.CustomProviders.format.ps1xml @@ -0,0 +1,521 @@ + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.CustomProvidersIdentity + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.CustomProvidersIdentity + + + + + + + + + + + + + + + + + + + + + + + + AssociationName + + + ResourceGroupName + + + ResourceProviderName + + + Scope + + + SubscriptionId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Association + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Association + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationProperties + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationProperties + + + + + + + + + + + + + + + ProvisioningState + + + TargetResourceId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationsList + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationsList + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpActionRouteDefinition + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpActionRouteDefinition + + + + + + + + + + + + + + + + + + Endpoint + + + Name + + + RoutingType + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifest + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifest + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestProperties + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestProperties + + + + + + + + + + + + ProvisioningState + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpResourceTypeRouteDefinition + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpResourceTypeRouteDefinition + + + + + + + + + + + + + + + + + + Endpoint + + + Name + + + RoutingType + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpRouteDefinition + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpRouteDefinition + + + + + + + + + + + + + + + Endpoint + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpValidations + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpValidations + + + + + + + + + + + + + + + Specification + + + ValidationType + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinition + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinition + + + + + + + + + + + + + + + Code + + + Message + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ListByCustomRpManifest + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ListByCustomRpManifest + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Resource + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Resource + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperation + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperation + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationDisplay + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationDisplay + + + + + + + + + + + + + + + + + + + + + Description + + + Operation + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationList + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationList + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdateTags + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdateTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags + + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags + + + + + + + + + + + + Item + + + + + + + + \ No newline at end of file diff --git a/src/CustomProviders/Az.CustomProviders.psd1 b/src/CustomProviders/Az.CustomProviders.psd1 new file mode 100644 index 000000000000..a592b7aa5ce9 --- /dev/null +++ b/src/CustomProviders/Az.CustomProviders.psd1 @@ -0,0 +1,25 @@ +@{ + GUID = 'b98dded0-6e9a-4371-b2c6-d74464fb724b' + RootModule = './Az.CustomProviders.psm1' + ModuleVersion = '0.1.0' + CompatiblePSEditions = 'Core', 'Desktop' + Author = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' + Copyright = 'Microsoft Corporation. All rights reserved.' + Description = 'Microsoft Azure PowerShell: Custom Providers cmdlets' + PowerShellVersion = '5.1' + DotNetFrameworkVersion = '4.7.2' + RequiredAssemblies = './bin/Az.CustomProviders.private.dll' + RequiredModules = @(@{ModuleName = 'Az.Accounts'; ModuleVersion = '1.9.0'; }) + FormatsToProcess = './Az.CustomProviders.format.ps1xml' + FunctionsToExport = 'Get-AzCustomProvider', 'Get-AzCustomProviderAssociation', 'New-AzCustomProvider', 'New-AzCustomProviderAssociation', 'Remove-AzCustomProvider', 'Remove-AzCustomProviderAssociation', 'Update-AzCustomProvider' + AliasesToExport = '*' + PrivateData = @{ + PSData = @{ + Tags = 'Azure', 'ResourceManager', 'ARM', 'PSModule', 'CustomProviders' + LicenseUri = 'https://aka.ms/azps-license' + ProjectUri = 'https://github.com/Azure/azure-powershell' + ReleaseNotes = '* the first preview release' + } + } +} diff --git a/src/CustomProviders/Az.CustomProviders.psm1 b/src/CustomProviders/Az.CustomProviders.psm1 new file mode 100644 index 000000000000..a9194bd2f679 --- /dev/null +++ b/src/CustomProviders/Az.CustomProviders.psm1 @@ -0,0 +1,109 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # + # Copyright Microsoft Corporation + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # http://www.apache.org/licenses/LICENSE-2.0 + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'1.8.1' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 1.8.1 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 1.8.1 or greater. For installation instructions, please see: https://docs.microsoft.com/en-us/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'1.8.1') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 1.8.1 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to remove '.PSSharedModules' in your home directory. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.CustomProviders.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.CustomProviders.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/CustomProviders/ChangeLog.md b/src/CustomProviders/ChangeLog.md new file mode 100644 index 000000000000..b76ecb79cf4a --- /dev/null +++ b/src/CustomProviders/ChangeLog.md @@ -0,0 +1,24 @@ + +## Upcoming Release + +## Version 0.1.0 +* the first preview release + diff --git a/src/CustomProviders/CustomProviders.sln b/src/CustomProviders/CustomProviders.sln new file mode 100644 index 000000000000..efac7d7aba04 --- /dev/null +++ b/src/CustomProviders/CustomProviders.sln @@ -0,0 +1,48 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Accounts", "..\Accounts\Accounts\Accounts.csproj", "{142D7B0B-388A-4CEB-A228-7F6D423C5C2E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication", "..\Accounts\Authentication\Authentication.csproj", "{62843FE6-7575-4D88-B989-7DF7EEC0BC01}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication.ResourceManager", "..\Accounts\Authentication.ResourceManager\Authentication.ResourceManager.csproj", "{442C609B-A431-4A71-B289-08F0B63C83E5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authenticators", "..\Accounts\Authenticators\Authenticators.csproj", "{59E8F6B8-8F0E-403F-B88B-9736DBC396D9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Az.CustomProviders", "Az.CustomProviders.csproj", "{D9A3D0D2-620B-4073-BF1B-AC5CF64247E5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.Build.0 = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.Build.0 = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.Build.0 = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.Build.0 = Release|Any CPU + {D9A3D0D2-620B-4073-BF1B-AC5CF64247E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D9A3D0D2-620B-4073-BF1B-AC5CF64247E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D9A3D0D2-620B-4073-BF1B-AC5CF64247E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D9A3D0D2-620B-4073-BF1B-AC5CF64247E5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F9B3D96E-9680-40BE-A917-02EE655D6030} + EndGlobalSection +EndGlobal diff --git a/src/CustomProviders/MSSharedLibKey.snk b/src/CustomProviders/MSSharedLibKey.snk new file mode 100644 index 000000000000..695f1b38774e Binary files /dev/null and b/src/CustomProviders/MSSharedLibKey.snk differ diff --git a/src/CustomProviders/Properties/AssemblyInfo.cs b/src/CustomProviders/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..f8706c4849e5 --- /dev/null +++ b/src/CustomProviders/Properties/AssemblyInfo.cs @@ -0,0 +1,28 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Microsoft Azure Powershell - CustomProviders")] +[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] +[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] +[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] + +[assembly: ComVisible(false)] +[assembly: CLSCompliant(false)] +[assembly: Guid("FE65990B-233F-4FC2-A873-4940FA015353")] +[assembly: AssemblyVersion("0.1.0")] +[assembly: AssemblyFileVersion("0.1.0")] \ No newline at end of file diff --git a/src/CustomProviders/build-module.ps1 b/src/CustomProviders/build-module.ps1 new file mode 100644 index 000000000000..10b8770e18ff --- /dev/null +++ b/src/CustomProviders/build-module.ps1 @@ -0,0 +1,153 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $Isolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.CustomProviders.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.CustomProviders.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.CustomProviders.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.CustomProviders' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: Custom Providers cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.CustomProviders.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/src/CustomProviders/check-dependencies.ps1 b/src/CustomProviders/check-dependencies.ps1 new file mode 100644 index 000000000000..513c52ca2fb5 --- /dev/null +++ b/src/CustomProviders/check-dependencies.ps1 @@ -0,0 +1,64 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [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)) { + $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 '1.8.1' +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))) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest-beta .\readme.md --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/src/CustomProviders/custom/Az.CustomProviders.custom.psm1 b/src/CustomProviders/custom/Az.CustomProviders.custom.psm1 new file mode 100644 index 000000000000..4c11da97863c --- /dev/null +++ b/src/CustomProviders/custom/Az.CustomProviders.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.CustomProviders.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.CustomProviders.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/CustomProviders/custom/readme.md b/src/CustomProviders/custom/readme.md new file mode 100644 index 000000000000..b484716e6b20 --- /dev/null +++ b/src/CustomProviders/custom/readme.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.CustomProviders` 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.CustomProviders.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.CustomProviders` 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.CustomProviders.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.CustomProviders.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundemental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.CustomProviders`. 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.CustomProviders.Models.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propegated to reference documentation via [help comments](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.CustomProviders`. +- `Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.CustomProviders`. For more information, see [readme.md](..\internal/readme.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ProfileAttribute` + - Used in C# and script cmdlets to define which Azure profiles the cmdlet supports. This is only supported for Azure (`--azure`) modules. \ No newline at end of file diff --git a/src/CustomProviders/examples/Get-AzCustomProvider.md b/src/CustomProviders/examples/Get-AzCustomProvider.md new file mode 100644 index 000000000000..30cf6d0b5711 --- /dev/null +++ b/src/CustomProviders/examples/Get-AzCustomProvider.md @@ -0,0 +1,30 @@ +### Example 1: List all Custom Providers in a subscription +```powershell +PS C:\> Get-AzCustomProvider + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +East US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders +``` + +Lists all the custom providers in a subscription + +### Example 2: Get a single custom provider +```powershell +PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : + +``` + +Gets details for a single custom provider. Use Format-List to show object details on the screen. + diff --git a/src/CustomProviders/examples/Get-AzCustomProviderAssociation.md b/src/CustomProviders/examples/Get-AzCustomProviderAssociation.md new file mode 100644 index 000000000000..ef2195718c6a --- /dev/null +++ b/src/CustomProviders/examples/Get-AzCustomProviderAssociation.md @@ -0,0 +1,22 @@ +### Example 1: List custom provider associations +```powershell +PS C:\> Get-AzCustomProviderAssociation + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +``` + +List all custom provider associations for a given scope. + +### Example 2: Get an association +```powershell +PS C:\> Get-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +``` + +Get details for a single CustomProvider association + diff --git a/src/CustomProviders/examples/New-AzCustomProvider.md b/src/CustomProviders/examples/New-AzCustomProvider.md new file mode 100644 index 000000000000..5649102b1b22 --- /dev/null +++ b/src/CustomProviders/examples/New-AzCustomProvider.md @@ -0,0 +1,23 @@ +### Example 1: Create a custom provider +```powershell +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"} + + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +``` + +Create a custom resource provider + +### Example 2: Create a custom provider with associations +```powershell +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace2.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"}, @{Name="Associations"; Endpoint="https://contoso.com/myService", RoutingType="Proxy,Cache,Extension"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders +``` + +Create a custom provider, with a route for Custom provider associations. + diff --git a/src/CustomProviders/examples/New-AzCustomProviderAssociation.md b/src/CustomProviders/examples/New-AzCustomProviderAssociation.md new file mode 100644 index 000000000000..a3a0eebac888 --- /dev/null +++ b/src/CustomProviders/examples/New-AzCustomProviderAssociation.md @@ -0,0 +1,12 @@ +### Example 1: Create a custom provider association +```powershell +PS C:\> $provider = Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +PS C:\> New-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc -TargetResourceId $provider.Id + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +``` + +Create a custom provider association, the associated target provioder must be properly configured with a route for "associations" + diff --git a/src/CustomProviders/examples/Remove-AzCustomProvider.md b/src/CustomProviders/examples/Remove-AzCustomProvider.md new file mode 100644 index 000000000000..e80cabf22050 --- /dev/null +++ b/src/CustomProviders/examples/Remove-AzCustomProvider.md @@ -0,0 +1,15 @@ +### Example 1: Remove a custom provider. +```powershell +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +``` + +Remove a custom provider + +### Example 2: Remove a custom provider with PassThru +```powershell +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -PassThru + +True +``` + +Remove a custom provider, using the PassThru feature to indicate success or failure. diff --git a/src/CustomProviders/examples/Remove-AzCustomProviderAssociation.md b/src/CustomProviders/examples/Remove-AzCustomProviderAssociation.md new file mode 100644 index 000000000000..5d9c8e1e0b0a --- /dev/null +++ b/src/CustomProviders/examples/Remove-AzCustomProviderAssociation.md @@ -0,0 +1,16 @@ +### Example 1: Remove a custom provider association. +```powershell +PS C:\> PS C:\> Remove-AzCustomProviderAssociation -Scope $id -Name Namespace.Type +``` + +Remove a custom provider association. + +### Example 2: Remove a custom provider association with Piping +```powershell +PS C:\> PS C:\> Get-AzCustomProviderAssociation | Remove-AzCustomProviderAssociation -PassThru + +True +``` + +Remove a custom provider association, using piping and the PassThru feature to indicate success or failure. + diff --git a/src/CustomProviders/examples/Update-AzCustomProvider.md b/src/CustomProviders/examples/Update-AzCustomProvider.md new file mode 100644 index 000000000000..f9d841d341b2 --- /dev/null +++ b/src/CustomProviders/examples/Update-AzCustomProvider.md @@ -0,0 +1,28 @@ +### Example 1: Add Tags to a custom Provider +```powershell +PS C:\> Update-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -Tag @{MyTag="MyValue"} | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : +``` + +Update the tags of a custom provider. + +### Example 2: Update custom provider with piping +```powershell +PS C:\> PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Update-AzCustomProvider -Tag @{MyTag="MyValue"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +``` + +Update a custom provider using piping. + diff --git a/src/CustomProviders/export-surface.ps1 b/src/CustomProviders/export-surface.ps1 new file mode 100644 index 000000000000..4002e0a2ee80 --- /dev/null +++ b/src/CustomProviders/export-surface.ps1 @@ -0,0 +1,40 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.CustomProviders.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.CustomProviders' +$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/CustomProviders/exports/Get-AzCustomProvider.ps1 b/src/CustomProviders/exports/Get-AzCustomProvider.ps1 new file mode 100644 index 000000000000..4c7d3bc0beed --- /dev/null +++ b/src/CustomProviders/exports/Get-AzCustomProvider.ps1 @@ -0,0 +1,185 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets the custom resource provider manifest. +.Description +Gets the custom resource provider manifest. +.Example +PS C:\> Get-AzCustomProvider + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +East US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders +.Example +PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azcustomprovider +#> +function Get-AzCustomProvider { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest])] +[CmdletBinding(DefaultParameterSetName='List1', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.CustomProviders.private\Get-AzCustomProvider_Get'; + GetViaIdentity = 'Az.CustomProviders.private\Get-AzCustomProvider_GetViaIdentity'; + List = 'Az.CustomProviders.private\Get-AzCustomProvider_List'; + List1 = 'Az.CustomProviders.private\Get-AzCustomProvider_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/CustomProviders/exports/Get-AzCustomProviderAssociation.ps1 b/src/CustomProviders/exports/Get-AzCustomProviderAssociation.ps1 new file mode 100644 index 000000000000..409effd161e1 --- /dev/null +++ b/src/CustomProviders/exports/Get-AzCustomProviderAssociation.ps1 @@ -0,0 +1,162 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Get an association. +.Description +Get an association. +.Example +PS C:\> Get-AzCustomProviderAssociation + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +.Example +PS C:\> Get-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azcustomproviderassociation +#> +function Get-AzCustomProviderAssociation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('AssociationName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the association. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The scope of the association. + ${Scope}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.CustomProviders.private\Get-AzCustomProviderAssociation_Get'; + GetViaIdentity = 'Az.CustomProviders.private\Get-AzCustomProviderAssociation_GetViaIdentity'; + List = 'Az.CustomProviders.private\Get-AzCustomProviderAssociation_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/CustomProviders/exports/New-AzCustomProvider.ps1 b/src/CustomProviders/exports/New-AzCustomProvider.ps1 new file mode 100644 index 000000000000..49f6e2407421 --- /dev/null +++ b/src/CustomProviders/exports/New-AzCustomProvider.ps1 @@ -0,0 +1,215 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates or updates the custom resource provider. +.Description +Creates or updates the custom resource provider. +.Example +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"} + + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +.Example +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace2.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"}, @{Name="Associations"; Endpoint="https://contoso.com/myService", RoutingType="Proxy,Cache,Extension"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest +.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. + +ACTION : A list of actions that the custom resource provider implements. + Endpoint : The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + Name : The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + [RoutingType ]: The routing types that are supported for action requests. + +RESOURCETYPE : A list of resource types that the custom resource provider implements. + Endpoint : The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + Name : The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + [RoutingType ]: The routing types that are supported for resource requests. + +VALIDATION : A list of validations to run on the custom resource provider's requests. + Specification : A link to the validation specification. The specification must be hosted on raw.githubusercontent.com. + [ValidationType ]: The type of validation to run against a matching request. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/new-azcustomprovider +#> +function New-AzCustomProvider { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [System.String] + # Resource location + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[]] + # A list of actions that the custom resource provider implements. + # To construct, see NOTES section for ACTION properties and create a hash table. + ${Action}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[]] + # A list of resource types that the custom resource provider implements. + # To construct, see NOTES section for RESOURCETYPE properties and create a hash table. + ${ResourceType}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[]] + # A list of validations to run on the custom resource provider's requests. + # To construct, see NOTES section for VALIDATION properties and create a hash table. + ${Validation}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.CustomProviders.private\New-AzCustomProvider_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/CustomProviders/exports/New-AzCustomProviderAssociation.ps1 b/src/CustomProviders/exports/New-AzCustomProviderAssociation.ps1 new file mode 100644 index 000000000000..e64013e7ec10 --- /dev/null +++ b/src/CustomProviders/exports/New-AzCustomProviderAssociation.ps1 @@ -0,0 +1,153 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create or update an association. +.Description +Create or update an association. +.Example +PS C:\> $provider = Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +PS C:\> New-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc -TargetResourceId $provider.Id + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/new-azcustomproviderassociation +#> +function New-AzCustomProviderAssociation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('AssociationName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the association. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The scope of the association. + # The scope can be any valid REST resource instance. + # For example, use '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' for a virtual machine resource. + ${Scope}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [System.String] + # The REST resource instance of the target resource for this association. + ${TargetResourceId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.CustomProviders.private\New-AzCustomProviderAssociation_CreateExpanded'; + } + $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/CustomProviders/exports/ProxyCmdletDefinitions.ps1 b/src/CustomProviders/exports/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..963a6b028d54 --- /dev/null +++ b/src/CustomProviders/exports/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,1258 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Get an association. +.Description +Get an association. +.Example +PS C:\> Get-AzCustomProviderAssociation + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +.Example +PS C:\> Get-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azcustomproviderassociation +#> +function Get-AzCustomProviderAssociation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('AssociationName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the association. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The scope of the association. + ${Scope}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.CustomProviders.private\Get-AzCustomProviderAssociation_Get'; + GetViaIdentity = 'Az.CustomProviders.private\Get-AzCustomProviderAssociation_GetViaIdentity'; + List = 'Az.CustomProviders.private\Get-AzCustomProviderAssociation_List'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets the custom resource provider manifest. +.Description +Gets the custom resource provider manifest. +.Example +PS C:\> Get-AzCustomProvider + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +East US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders +.Example +PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azcustomprovider +#> +function Get-AzCustomProvider { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest])] +[CmdletBinding(DefaultParameterSetName='List1', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.CustomProviders.private\Get-AzCustomProvider_Get'; + GetViaIdentity = 'Az.CustomProviders.private\Get-AzCustomProvider_GetViaIdentity'; + List = 'Az.CustomProviders.private\Get-AzCustomProvider_List'; + List1 = 'Az.CustomProviders.private\Get-AzCustomProvider_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create or update an association. +.Description +Create or update an association. +.Example +PS C:\> $provider = Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +PS C:\> New-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc -TargetResourceId $provider.Id + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/new-azcustomproviderassociation +#> +function New-AzCustomProviderAssociation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('AssociationName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the association. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The scope of the association. + # The scope can be any valid REST resource instance. + # For example, use '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' for a virtual machine resource. + ${Scope}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [System.String] + # The REST resource instance of the target resource for this association. + ${TargetResourceId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.CustomProviders.private\New-AzCustomProviderAssociation_CreateExpanded'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates or updates the custom resource provider. +.Description +Creates or updates the custom resource provider. +.Example +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"} + + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +.Example +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace2.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"}, @{Name="Associations"; Endpoint="https://contoso.com/myService", RoutingType="Proxy,Cache,Extension"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest +.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. + +ACTION : A list of actions that the custom resource provider implements. + Endpoint : The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + Name : The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + [RoutingType ]: The routing types that are supported for action requests. + +RESOURCETYPE : A list of resource types that the custom resource provider implements. + Endpoint : The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + Name : The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + [RoutingType ]: The routing types that are supported for resource requests. + +VALIDATION : A list of validations to run on the custom resource provider's requests. + Specification : A link to the validation specification. The specification must be hosted on raw.githubusercontent.com. + [ValidationType ]: The type of validation to run against a matching request. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/new-azcustomprovider +#> +function New-AzCustomProvider { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [System.String] + # Resource location + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[]] + # A list of actions that the custom resource provider implements. + # To construct, see NOTES section for ACTION properties and create a hash table. + ${Action}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[]] + # A list of resource types that the custom resource provider implements. + # To construct, see NOTES section for RESOURCETYPE properties and create a hash table. + ${ResourceType}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[]] + # A list of validations to run on the custom resource provider's requests. + # To construct, see NOTES section for VALIDATION properties and create a hash table. + ${Validation}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.CustomProviders.private\New-AzCustomProvider_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Delete an association. +.Description +Delete an association. +.Example +PS C:\> PS C:\> Remove-AzCustomProviderAssociation -Scope $id -Name Namespace.Type +.Example +PS C:\> PS C:\> Get-AzCustomProviderAssociation | Remove-AzCustomProviderAssociation -PassThru + +True + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/remove-azcustomproviderassociation +#> +function Remove-AzCustomProviderAssociation { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('AssociationName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the association. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The scope of the association. + ${Scope}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.CustomProviders.private\Remove-AzCustomProviderAssociation_Delete'; + DeleteViaIdentity = 'Az.CustomProviders.private\Remove-AzCustomProviderAssociation_DeleteViaIdentity'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes the custom resource provider. +.Description +Deletes the custom resource provider. +.Example +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +.Example +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -PassThru + +True + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/remove-azcustomprovider +#> +function Remove-AzCustomProvider { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.CustomProviders.private\Remove-AzCustomProvider_Delete'; + DeleteViaIdentity = 'Az.CustomProviders.private\Remove-AzCustomProvider_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Updates an existing custom resource provider. +The only value that can be updated via PATCH currently is the tags. +.Description +Updates an existing custom resource provider. +The only value that can be updated via PATCH currently is the tags. +.Example +PS C:\> Update-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -Tag @{MyTag="MyValue"} | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : +.Example +PS C:\> PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Update-AzCustomProvider -Tag @{MyTag="MyValue"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/update-azcustomprovider +#> +function Update-AzCustomProvider { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.CustomProviders.private\Update-AzCustomProvider_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.CustomProviders.private\Update-AzCustomProvider_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/CustomProviders/exports/Remove-AzCustomProvider.ps1 b/src/CustomProviders/exports/Remove-AzCustomProvider.ps1 new file mode 100644 index 000000000000..5167b8949f5b --- /dev/null +++ b/src/CustomProviders/exports/Remove-AzCustomProvider.ps1 @@ -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. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes the custom resource provider. +.Description +Deletes the custom resource provider. +.Example +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +.Example +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -PassThru + +True + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/remove-azcustomprovider +#> +function Remove-AzCustomProvider { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.CustomProviders.private\Remove-AzCustomProvider_Delete'; + DeleteViaIdentity = 'Az.CustomProviders.private\Remove-AzCustomProvider_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/CustomProviders/exports/Remove-AzCustomProviderAssociation.ps1 b/src/CustomProviders/exports/Remove-AzCustomProviderAssociation.ps1 new file mode 100644 index 000000000000..04bd8327520f --- /dev/null +++ b/src/CustomProviders/exports/Remove-AzCustomProviderAssociation.ps1 @@ -0,0 +1,172 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Delete an association. +.Description +Delete an association. +.Example +PS C:\> PS C:\> Remove-AzCustomProviderAssociation -Scope $id -Name Namespace.Type +.Example +PS C:\> PS C:\> Get-AzCustomProviderAssociation | Remove-AzCustomProviderAssociation -PassThru + +True + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/remove-azcustomproviderassociation +#> +function Remove-AzCustomProviderAssociation { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('AssociationName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the association. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The scope of the association. + ${Scope}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.CustomProviders.private\Remove-AzCustomProviderAssociation_Delete'; + DeleteViaIdentity = 'Az.CustomProviders.private\Remove-AzCustomProviderAssociation_DeleteViaIdentity'; + } + $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/CustomProviders/exports/Update-AzCustomProvider.ps1 b/src/CustomProviders/exports/Update-AzCustomProvider.ps1 new file mode 100644 index 000000000000..c246aa6421c4 --- /dev/null +++ b/src/CustomProviders/exports/Update-AzCustomProvider.ps1 @@ -0,0 +1,187 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Updates an existing custom resource provider. +The only value that can be updated via PATCH currently is the tags. +.Description +Updates an existing custom resource provider. +The only value that can be updated via PATCH currently is the tags. +.Example +PS C:\> Update-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -Tag @{MyTag="MyValue"} | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : +.Example +PS C:\> PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Update-AzCustomProvider -Tag @{MyTag="MyValue"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [AssociationName ]: The name of the association. + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [ResourceProviderName ]: The name of the resource provider. + [Scope ]: The scope of the association. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/update-azcustomprovider +#> +function Update-AzCustomProvider { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('ResourceProviderName')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource provider. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.CustomProviders.private\Update-AzCustomProvider_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.CustomProviders.private\Update-AzCustomProvider_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/CustomProviders/exports/readme.md b/src/CustomProviders/exports/readme.md new file mode 100644 index 000000000000..453313c3db7c --- /dev/null +++ b/src/CustomProviders/exports/readme.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.CustomProviders`. No other cmdlets in this repository are directly exported. What that means is the `Az.CustomProviders` module will run [Export-ModuleMember](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.CustomProviders.private.dll`) and from the `..\custom\Az.CustomProviders.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.CustomProviders.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/CustomProviders/generate-help.ps1 b/src/CustomProviders/generate-help.ps1 new file mode 100644 index 000000000000..af68789db1ac --- /dev/null +++ b/src/CustomProviders/generate-help.ps1 @@ -0,0 +1,73 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.CustomProviders.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.CustomProviders.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/CustomProviders/generate-info.json b/src/CustomProviders/generate-info.json new file mode 100644 index 000000000000..d51bff780b06 --- /dev/null +++ b/src/CustomProviders/generate-info.json @@ -0,0 +1,8 @@ +{ + "autorest": "`-- (empty)", + "autorest_core": "3.0.6282", + "swagger_commit": "cf34791021c7d8f2d988fc94a9306f29f4f66617", + "node": "v10.16.0", + "autorest_remodeler": "2.1.27", + "autorest_powershell": "2.1.396" +} diff --git a/src/CustomProviders/generated/Module.cs b/src/CustomProviders/generated/Module.cs new file mode 100644 index 000000000000..ef63ed04911e --- /dev/null +++ b/src/CustomProviders/generated/Module.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpPipeline _pipelineWithProxy; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// Backing field for property. + private static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module _instance; + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module Instance => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module._instance?? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module._instance = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module()); + + /// The Name of this module + public string Name => @"Az.CustomProviders"; + + /// 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.CustomProviders"; + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_handler.UseProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + } + + /// Creates the module instance. + private Module() + { + /// constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + _webProxy.UseDefaultCredentials = proxyUseDefaultCredentials; + _handler.UseProxy = proxy != null; + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/CustomProviders.cs b/src/CustomProviders/generated/api/CustomProviders.cs new file mode 100644 index 000000000000..79de6417d175 --- /dev/null +++ b/src/CustomProviders/generated/api/CustomProviders.cs @@ -0,0 +1,2183 @@ +// 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.CustomProviders +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// + /// Low-level API implementation for the CustomProviders service. + /// + public partial class CustomProviders + { + + /// Create or update an association. + /// The scope of the association. The scope can be any valid REST resource instance. For example, use + /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' + /// for a virtual machine resource. + /// The name of the association. + /// The parameters required to create or update an association. + /// 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.CustomProviders.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 AssociationsCreateOrUpdate(string scope, string associationName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + (scope) + + "/providers/Microsoft.CustomProviders/associations/" + + global::System.Uri.EscapeDataString(associationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Create or update an association. + /// + /// The parameters required to create or update an association. + /// 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.CustomProviders.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 AssociationsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/(?[^/]+)/providers/Microsoft.CustomProviders/associations/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}'"); + } + + // replace URI parameters with values from identity + var scope = _match.Groups["scope"].Value; + var associationName = _match.Groups["associationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + scope + + "/providers/Microsoft.CustomProviders/associations/" + + associationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 AssociationsCreateOrUpdate_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_originalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_originalUri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Association.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 of the association. The scope can be any valid REST resource instance. For example, use + /// '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' + /// for a virtual machine resource. + /// The name of the association. + /// The parameters required to create or update an association. + /// 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 AssociationsCreateOrUpdate_Validate(string scope, string associationName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation body, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(scope),scope); + await eventListener.AssertNotNull(nameof(associationName),associationName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete an association. + /// The scope of the association. + /// The name of the association. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 AssociationsDelete(string scope, string associationName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + (scope) + + "/providers/Microsoft.CustomProviders/associations/" + + global::System.Uri.EscapeDataString(associationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Delete an association. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 AssociationsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/(?[^/]+)/providers/Microsoft.CustomProviders/associations/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}'"); + } + + // replace URI parameters with values from identity + var scope = _match.Groups["scope"].Value; + var associationName = _match.Groups["associationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + scope + + "/providers/Microsoft.CustomProviders/associations/" + + associationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 AssociationsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var _finalUri = ""; + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_finalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 of the association. + /// The name of the association. + /// 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 AssociationsDelete_Validate(string scope, string associationName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(scope),scope); + await eventListener.AssertNotNull(nameof(associationName),associationName); + } + } + + /// Get an association. + /// The scope of the association. + /// The name of the association. + /// 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.CustomProviders.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 AssociationsGet(string scope, string associationName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + (scope) + + "/providers/Microsoft.CustomProviders/associations/" + + global::System.Uri.EscapeDataString(associationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Get an association. + /// + /// 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.CustomProviders.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 AssociationsGetViaIdentity(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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/(?[^/]+)/providers/Microsoft.CustomProviders/associations/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}'"); + } + + // replace URI parameters with values from identity + var scope = _match.Groups["scope"].Value; + var associationName = _match.Groups["associationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + scope + + "/providers/Microsoft.CustomProviders/associations/" + + associationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 AssociationsGet_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Association.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 of the association. + /// The name of the association. + /// 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 AssociationsGet_Validate(string scope, string associationName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(scope),scope); + await eventListener.AssertNotNull(nameof(associationName),associationName); + } + } + + /// Gets all association for the given scope. + /// The scope of the association. + /// 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.CustomProviders.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 AssociationsListAll(string scope, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + (scope) + + "/providers/Microsoft.CustomProviders/associations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsListAll_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets all association for the given 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.CustomProviders.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 AssociationsListAllViaIdentity(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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/(?[^/]+)/providers/Microsoft.CustomProviders/associations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/{scope}/providers/Microsoft.CustomProviders/associations'"); + } + + // replace URI parameters with values from identity + var scope = _match.Groups["scope"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + scope + + "/providers/Microsoft.CustomProviders/associations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.AssociationsListAll_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 AssociationsListAll_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationsList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 of the association. + /// 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 AssociationsListAll_Validate(string scope, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(scope),scope); + } + } + + /// Creates or updates the custom resource provider. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// The parameters required to create or update a custom resource provider definition. + /// 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.CustomProviders.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 CustomResourceProviderCreateOrUpdate(string subscriptionId, string resourceGroupName, string resourceProviderName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + global::System.Uri.EscapeDataString(resourceProviderName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Creates or updates the custom resource provider. + /// + /// The parameters required to create or update a custom resource provider definition. + /// 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.CustomProviders.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 CustomResourceProviderCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.CustomProviders/resourceProviders/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceProviderName = _match.Groups["resourceProviderName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + resourceProviderName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderCreateOrUpdate_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_originalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_originalUri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifest.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// The parameters required to create or update a custom resource provider definition. + /// 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 CustomResourceProviderCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string resourceProviderName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest body, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceProviderName),resourceProviderName); + await eventListener.AssertMinimumLength(nameof(resourceProviderName),resourceProviderName,3); + await eventListener.AssertMaximumLength(nameof(resourceProviderName),resourceProviderName,64); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the custom resource provider. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderDelete(string subscriptionId, string resourceGroupName, string resourceProviderName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + global::System.Uri.EscapeDataString(resourceProviderName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Deletes the custom resource provider. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.CustomProviders/resourceProviders/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceProviderName = _match.Groups["resourceProviderName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + resourceProviderName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var _finalUri = ""; + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_finalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// 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 CustomResourceProviderDelete_Validate(string subscriptionId, string resourceGroupName, string resourceProviderName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceProviderName),resourceProviderName); + await eventListener.AssertMinimumLength(nameof(resourceProviderName),resourceProviderName,3); + await eventListener.AssertMaximumLength(nameof(resourceProviderName),resourceProviderName,64); + } + } + + /// Gets the custom resource provider manifest. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// 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.CustomProviders.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 CustomResourceProviderGet(string subscriptionId, string resourceGroupName, string resourceProviderName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + global::System.Uri.EscapeDataString(resourceProviderName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets the custom resource provider manifest. + /// + /// 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.CustomProviders.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 CustomResourceProviderGetViaIdentity(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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.CustomProviders/resourceProviders/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceProviderName = _match.Groups["resourceProviderName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + resourceProviderName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderGet_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifest.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// 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 CustomResourceProviderGet_Validate(string subscriptionId, string resourceGroupName, string resourceProviderName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceProviderName),resourceProviderName); + await eventListener.AssertMinimumLength(nameof(resourceProviderName),resourceProviderName,3); + await eventListener.AssertMaximumLength(nameof(resourceProviderName),resourceProviderName,64); + } + } + + /// Gets all the custom resource providers within a resource group. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// 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.CustomProviders.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 CustomResourceProviderListByResourceGroup(string subscriptionId, string resourceGroupName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CustomProviders/resourceProviders" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets all the custom resource providers within a resource group. + /// + /// 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.CustomProviders.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 CustomResourceProviderListByResourceGroupViaIdentity(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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.CustomProviders/resourceProviders$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CustomProviders/resourceProviders" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderListByResourceGroup_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ListByCustomRpManifest.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// 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 CustomResourceProviderListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + } + } + + /// Gets all the custom resource providers within a subscription. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// 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.CustomProviders.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 CustomResourceProviderListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.CustomProviders/resourceProviders" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets all the custom resource providers within a subscription. + /// + /// 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.CustomProviders.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 CustomResourceProviderListBySubscriptionViaIdentity(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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.CustomProviders/resourceProviders$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.CustomProviders/resourceProviders'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.CustomProviders/resourceProviders" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderListBySubscription_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ListByCustomRpManifest.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// 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 CustomResourceProviderListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// + /// Updates an existing custom resource provider. The only value that can be updated via PATCH currently is the tags. + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// The updatable fields of a custom resource provider. + /// 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.CustomProviders.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 CustomResourceProviderUpdate(string subscriptionId, string resourceGroupName, string resourceProviderName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + global::System.Uri.EscapeDataString(resourceProviderName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Updates an existing custom resource provider. The only value that can be updated via PATCH currently is the tags. + /// + /// + /// The updatable fields of a custom resource provider. + /// 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.CustomProviders.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 CustomResourceProviderUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.CustomProviders/resourceProviders/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceProviderName = _match.Groups["resourceProviderName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CustomProviders/resourceProviders/" + + resourceProviderName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CustomResourceProviderUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 CustomResourceProviderUpdate_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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifest.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The name of the resource provider. + /// The updatable fields of a custom resource provider. + /// 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 CustomResourceProviderUpdate_Validate(string subscriptionId, string resourceGroupName, string resourceProviderName, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate body, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceProviderName),resourceProviderName); + await eventListener.AssertMinimumLength(nameof(resourceProviderName),resourceProviderName,3); + await eventListener.AssertMaximumLength(nameof(resourceProviderName),resourceProviderName,64); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// The list of operations provided by Microsoft CustomProviders. + /// 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.CustomProviders.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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.CustomProviders/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// The list of operations provided by Microsoft CustomProviders. + /// + /// 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.CustomProviders.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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-09-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.CustomProviders/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.CustomProviders/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.CustomProviders/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.PowerShell.cs new file mode 100644 index 000000000000..bd8f569dfce4 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.PowerShell.cs @@ -0,0 +1,141 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// The resource definition of this association. + [System.ComponentModel.TypeConverter(typeof(AssociationTypeConverter))] + public partial class Association + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Association(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).TargetResourceId, 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 Association(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal)this).TargetResourceId, 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.CustomProviders.Models.Api20180901Preview.IAssociation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Association(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.CustomProviders.Models.Api20180901Preview.IAssociation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Association(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.CustomProviders.Models.Api20180901Preview.IAssociation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The resource definition of this association. + [System.ComponentModel.TypeConverter(typeof(AssociationTypeConverter))] + public partial interface IAssociation + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.TypeConverter.cs new file mode 100644 index 000000000000..082cdf073dd8 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AssociationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Association.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Association.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Association.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/CustomProviders/generated/api/Models/Api20180901Preview/Association.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.cs new file mode 100644 index 000000000000..73b1c84155f8 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.cs @@ -0,0 +1,132 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The resource definition of this association. + public partial class Association : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal + { + + /// Backing field for property. + private string _id; + + /// The association id. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The association name. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties _property; + + /// The properties of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationProperties()); set => this._property = value; } + + /// The provisioning state of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)Property).ProvisioningState; } + + /// The REST resource instance of the target resource for this association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public string TargetResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)Property).TargetResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)Property).TargetResourceId = value; } + + /// Backing field for property. + private string _type; + + /// The association type. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Association() + { + + } + } + /// The resource definition of this association. + public partial interface IAssociation : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// The association id. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The association id.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// The association name. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The association name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The provisioning state of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the association.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; } + /// The REST resource instance of the target resource for this association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The REST resource instance of the target resource for this association.", + SerializedName = @"targetResourceId", + PossibleTypes = new [] { typeof(string) })] + string TargetResourceId { get; set; } + /// The association type. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The association type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The resource definition of this association. + internal partial interface IAssociationInternal + + { + /// The association id. + string Id { get; set; } + /// The association name. + string Name { get; set; } + /// The properties of the association. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties Property { get; set; } + /// The provisioning state of the association. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; set; } + /// The REST resource instance of the target resource for this association. + string TargetResourceId { get; set; } + /// The association type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.json.cs new file mode 100644 index 000000000000..ffb5b9a1f3d9 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Association.json.cs @@ -0,0 +1,116 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The resource definition of this association. + public partial class Association + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal Association(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationProperties.FromJson(__jsonProperties) : Property;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new Association(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.PowerShell.cs new file mode 100644 index 000000000000..4547d6050ac1 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// The properties of the association. + [System.ComponentModel.TypeConverter(typeof(AssociationPropertiesTypeConverter))] + public partial class AssociationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal AssociationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).TargetResourceId, 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 AssociationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).TargetResourceId = (string) content.GetValueForProperty("TargetResourceId",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal)this).TargetResourceId, 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.CustomProviders.Models.Api20180901Preview.IAssociationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AssociationProperties(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.CustomProviders.Models.Api20180901Preview.IAssociationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AssociationProperties(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.CustomProviders.Models.Api20180901Preview.IAssociationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The properties of the association. + [System.ComponentModel.TypeConverter(typeof(AssociationPropertiesTypeConverter))] + public partial interface IAssociationProperties + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.TypeConverter.cs new file mode 100644 index 000000000000..cfcc8269284a --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AssociationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AssociationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AssociationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AssociationProperties.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/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.cs new file mode 100644 index 000000000000..f2e8b053cc85 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.cs @@ -0,0 +1,66 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The properties of the association. + public partial class AssociationProperties : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal + { + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? _provisioningState; + + /// The provisioning state of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _targetResourceId; + + /// The REST resource instance of the target resource for this association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string TargetResourceId { get => this._targetResourceId; set => this._targetResourceId = value; } + + /// Creates an new instance. + public AssociationProperties() + { + + } + } + /// The properties of the association. + public partial interface IAssociationProperties : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// The provisioning state of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the association.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; } + /// The REST resource instance of the target resource for this association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The REST resource instance of the target resource for this association.", + SerializedName = @"targetResourceId", + PossibleTypes = new [] { typeof(string) })] + string TargetResourceId { get; set; } + + } + /// The properties of the association. + internal partial interface IAssociationPropertiesInternal + + { + /// The provisioning state of the association. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; set; } + /// The REST resource instance of the target resource for this association. + string TargetResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.json.cs new file mode 100644 index 000000000000..7dfc9033c666 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationProperties.json.cs @@ -0,0 +1,106 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The properties of the association. + public partial class AssociationProperties + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal AssociationProperties(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + {_targetResourceId = If( json?.PropertyT("targetResourceId"), out var __jsonTargetResourceId) ? (string)__jsonTargetResourceId : (string)TargetResourceId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new AssociationProperties(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AddIf( null != (((object)this._targetResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._targetResourceId.ToString()) : null, "targetResourceId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.PowerShell.cs new file mode 100644 index 000000000000..84ca4ac0f9df --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// List of associations. + [System.ComponentModel.TypeConverter(typeof(AssociationsListTypeConverter))] + public partial class AssociationsList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal AssociationsList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AssociationsList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.AssociationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AssociationsList(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.CustomProviders.Models.Api20180901Preview.IAssociationsList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AssociationsList(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.CustomProviders.Models.Api20180901Preview.IAssociationsList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// List of associations. + [System.ComponentModel.TypeConverter(typeof(AssociationsListTypeConverter))] + public partial interface IAssociationsList + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.TypeConverter.cs new file mode 100644 index 000000000000..7b4b68249d06 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AssociationsListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AssociationsList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AssociationsList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AssociationsList.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/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.cs new file mode 100644 index 000000000000..2da3cc4d144d --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// List of associations. + public partial class AssociationsList : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsList, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsListInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to use for getting the next set of results. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation[] _value; + + /// The array of associations. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public AssociationsList() + { + + } + } + /// List of associations. + public partial interface IAssociationsList : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// The URL to use for getting the next set of results. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to use for getting the next set of results.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The array of associations. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The array of associations.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation[] Value { get; set; } + + } + /// List of associations. + internal partial interface IAssociationsListInternal + + { + /// The URL to use for getting the next set of results. + string NextLink { get; set; } + /// The array of associations. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.json.cs new file mode 100644 index 000000000000..289259ffb5f0 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/AssociationsList.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// List of associations. + public partial class AssociationsList + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal AssociationsList(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation) (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Association.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociationsList FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new AssociationsList(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.PowerShell.cs new file mode 100644 index 000000000000..442dbb15d52f --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// The route definition for an action implemented by the custom resource provider. + [System.ComponentModel.TypeConverter(typeof(CustomRpActionRouteDefinitionTypeConverter))] + public partial class CustomRpActionRouteDefinition + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CustomRpActionRouteDefinition(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinitionInternal)this).RoutingType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting?) content.GetValueForProperty("RoutingType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinitionInternal)this).RoutingType, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CustomRpActionRouteDefinition(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinitionInternal)this).RoutingType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting?) content.GetValueForProperty("RoutingType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinitionInternal)this).RoutingType, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CustomRpActionRouteDefinition(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.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CustomRpActionRouteDefinition(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.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The route definition for an action implemented by the custom resource provider. + [System.ComponentModel.TypeConverter(typeof(CustomRpActionRouteDefinitionTypeConverter))] + public partial interface ICustomRpActionRouteDefinition + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.TypeConverter.cs new file mode 100644 index 000000000000..4a0a77f078b1 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CustomRpActionRouteDefinitionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CustomRpActionRouteDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CustomRpActionRouteDefinition.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CustomRpActionRouteDefinition.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/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.cs new file mode 100644 index 000000000000..7b4e2aa70fc7 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.cs @@ -0,0 +1,78 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The route definition for an action implemented by the custom resource provider. + public partial class CustomRpActionRouteDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinitionInternal, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition __customRpRouteDefinition = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpRouteDefinition(); + + /// + /// The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of + /// a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Endpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Endpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Endpoint = value; } + + /// + /// The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Name = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting? _routingType; + + /// The routing types that are supported for action requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting? RoutingType { get => this._routingType; set => this._routingType = value; } + + /// Creates an new instance. + public CustomRpActionRouteDefinition() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__customRpRouteDefinition), __customRpRouteDefinition); + await eventListener.AssertObjectIsValid(nameof(__customRpRouteDefinition), __customRpRouteDefinition); + } + } + /// The route definition for an action implemented by the custom resource provider. + public partial interface ICustomRpActionRouteDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition + { + /// The routing types that are supported for action requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The routing types that are supported for action requests.", + SerializedName = @"routingType", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting? RoutingType { get; set; } + + } + /// The route definition for an action implemented by the custom resource provider. + internal partial interface ICustomRpActionRouteDefinitionInternal : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal + { + /// The routing types that are supported for action requests. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting? RoutingType { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.json.cs new file mode 100644 index 000000000000..6e55f18598ba --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpActionRouteDefinition.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The route definition for an action implemented by the custom resource provider. + public partial class CustomRpActionRouteDefinition + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal CustomRpActionRouteDefinition(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __customRpRouteDefinition = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpRouteDefinition(json); + {_routingType = If( json?.PropertyT("routingType"), out var __jsonRoutingType) ? (string)__jsonRoutingType : (string)RoutingType;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new CustomRpActionRouteDefinition(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __customRpRouteDefinition?.ToJson(container, serializationMode); + AddIf( null != (((object)this._routingType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._routingType.ToString()) : null, "routingType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.PowerShell.cs new file mode 100644 index 000000000000..bff17bd74954 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.PowerShell.cs @@ -0,0 +1,151 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// A manifest file that defines the custom resource provider resources. + [System.ComponentModel.TypeConverter(typeof(CustomRpManifestTypeConverter))] + public partial class CustomRpManifest + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CustomRpManifest(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Action = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[]) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Action, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpActionRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ResourceType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[]) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ResourceType, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpResourceTypeRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Validation = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[]) content.GetValueForProperty("Validation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Validation, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpValidationsTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CustomRpManifest(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Action = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[]) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Action, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpActionRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ResourceType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[]) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).ResourceType, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpResourceTypeRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Validation = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[]) content.GetValueForProperty("Validation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal)this).Validation, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpValidationsTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CustomRpManifest(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.CustomProviders.Models.Api20180901Preview.ICustomRpManifest DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CustomRpManifest(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.CustomProviders.Models.Api20180901Preview.ICustomRpManifest FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// A manifest file that defines the custom resource provider resources. + [System.ComponentModel.TypeConverter(typeof(CustomRpManifestTypeConverter))] + public partial interface ICustomRpManifest + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.TypeConverter.cs new file mode 100644 index 000000000000..58c477a9f7ac --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CustomRpManifestTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CustomRpManifest.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CustomRpManifest.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CustomRpManifest.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/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.cs new file mode 100644 index 000000000000..69f87d37b0b1 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.cs @@ -0,0 +1,148 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// A manifest file that defines the custom resource provider resources. + public partial class CustomRpManifest : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Resource(); + + /// A list of actions that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] Action { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).Action; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).Action = value; } + + /// Resource Id + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Id; } + + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Location = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Type = value; } + + /// Resource name + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties _property; + + /// The manifest for the custom resource provider + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestProperties()); set => this._property = value; } + + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).ProvisioningState; } + + /// A list of resource types that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] ResourceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).ResourceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).ResourceType = value; } + + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Tag = value; } + + /// Resource type + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)__resource).Type; } + + /// A list of validations to run on the custom resource provider's requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] Validation { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).Validation; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)Property).Validation = value; } + + /// Creates an new instance. + public CustomRpManifest() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// A manifest file that defines the custom resource provider resources. + public partial interface ICustomRpManifest : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResource + { + /// A list of actions that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of actions that the custom resource provider implements.", + SerializedName = @"actions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] Action { get; set; } + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the resource provider.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; } + /// A list of resource types that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of resource types that the custom resource provider implements.", + SerializedName = @"resourceTypes", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] ResourceType { get; set; } + /// A list of validations to run on the custom resource provider's requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of validations to run on the custom resource provider's requests.", + SerializedName = @"validations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] Validation { get; set; } + + } + /// A manifest file that defines the custom resource provider resources. + internal partial interface ICustomRpManifestInternal : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal + { + /// A list of actions that the custom resource provider implements. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] Action { get; set; } + /// The manifest for the custom resource provider + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties Property { get; set; } + /// The provisioning state of the resource provider. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; set; } + /// A list of resource types that the custom resource provider implements. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] ResourceType { get; set; } + /// A list of validations to run on the custom resource provider's requests. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] Validation { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.json.cs new file mode 100644 index 000000000000..9c810a591bfb --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifest.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// A manifest file that defines the custom resource provider resources. + public partial class CustomRpManifest + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal CustomRpManifest(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Resource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestProperties.FromJson(__jsonProperties) : Property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new CustomRpManifest(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.PowerShell.cs new file mode 100644 index 000000000000..751d97d10c42 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// The manifest for the custom resource provider + [System.ComponentModel.TypeConverter(typeof(CustomRpManifestPropertiesTypeConverter))] + public partial class CustomRpManifestProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CustomRpManifestProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Action = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[]) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Action, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpActionRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ResourceType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[]) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ResourceType, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpResourceTypeRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Validation = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[]) content.GetValueForProperty("Validation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Validation, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpValidationsTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CustomRpManifestProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Action = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[]) content.GetValueForProperty("Action",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Action, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpActionRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ResourceType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[]) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).ResourceType, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpResourceTypeRouteDefinitionTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Validation = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[]) content.GetValueForProperty("Validation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal)this).Validation, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpValidationsTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CustomRpManifestProperties(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.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CustomRpManifestProperties(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.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The manifest for the custom resource provider + [System.ComponentModel.TypeConverter(typeof(CustomRpManifestPropertiesTypeConverter))] + public partial interface ICustomRpManifestProperties + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.TypeConverter.cs new file mode 100644 index 000000000000..4f82f4774d45 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CustomRpManifestPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CustomRpManifestProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CustomRpManifestProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CustomRpManifestProperties.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/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.cs new file mode 100644 index 000000000000..d0cf6c05cd3b --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.cs @@ -0,0 +1,100 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The manifest for the custom resource provider + public partial class CustomRpManifestProperties : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] _action; + + /// A list of actions that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] Action { get => this._action; set => this._action = value; } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? _provisioningState; + + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] _resourceType; + + /// A list of resource types that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] ResourceType { get => this._resourceType; set => this._resourceType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] _validation; + + /// A list of validations to run on the custom resource provider's requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] Validation { get => this._validation; set => this._validation = value; } + + /// Creates an new instance. + public CustomRpManifestProperties() + { + + } + } + /// The manifest for the custom resource provider + public partial interface ICustomRpManifestProperties : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// A list of actions that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of actions that the custom resource provider implements.", + SerializedName = @"actions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] Action { get; set; } + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the resource provider.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; } + /// A list of resource types that the custom resource provider implements. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of resource types that the custom resource provider implements.", + SerializedName = @"resourceTypes", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] ResourceType { get; set; } + /// A list of validations to run on the custom resource provider's requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of validations to run on the custom resource provider's requests.", + SerializedName = @"validations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] Validation { get; set; } + + } + /// The manifest for the custom resource provider + internal partial interface ICustomRpManifestPropertiesInternal + + { + /// A list of actions that the custom resource provider implements. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] Action { get; set; } + /// The provisioning state of the resource provider. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState? ProvisioningState { get; set; } + /// A list of resource types that the custom resource provider implements. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] ResourceType { get; set; } + /// A list of validations to run on the custom resource provider's requests. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] Validation { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.json.cs new file mode 100644 index 000000000000..d64bb3557c29 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpManifestProperties.json.cs @@ -0,0 +1,134 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The manifest for the custom resource provider + public partial class CustomRpManifestProperties + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal CustomRpManifestProperties(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_action = If( json?.PropertyT("actions"), out var __jsonActions) ? If( __jsonActions as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition) (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpActionRouteDefinition.FromJson(__u) )) ))() : null : Action;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + {_resourceType = If( json?.PropertyT("resourceTypes"), out var __jsonResourceTypes) ? If( __jsonResourceTypes as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonArray, out var __q) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition) (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpResourceTypeRouteDefinition.FromJson(__p) )) ))() : null : ResourceType;} + {_validation = If( json?.PropertyT("validations"), out var __jsonValidations) ? If( __jsonValidations as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonArray, out var __l) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations) (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpValidations.FromJson(__k) )) ))() : null : Validation;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifestProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new CustomRpManifestProperties(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._action) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.XNodeArray(); + foreach( var __x in this._action ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("actions",__w); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (null != this._resourceType) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.XNodeArray(); + foreach( var __s in this._resourceType ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("resourceTypes",__r); + } + if (null != this._validation) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.XNodeArray(); + foreach( var __n in this._validation ) + { + AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); + } + container.Add("validations",__m); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.PowerShell.cs new file mode 100644 index 000000000000..c849e44da382 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// The route definition for a resource implemented by the custom resource provider. + /// + [System.ComponentModel.TypeConverter(typeof(CustomRpResourceTypeRouteDefinitionTypeConverter))] + public partial class CustomRpResourceTypeRouteDefinition + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CustomRpResourceTypeRouteDefinition(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinitionInternal)this).RoutingType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting?) content.GetValueForProperty("RoutingType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinitionInternal)this).RoutingType, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CustomRpResourceTypeRouteDefinition(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinitionInternal)this).RoutingType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting?) content.GetValueForProperty("RoutingType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinitionInternal)this).RoutingType, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CustomRpResourceTypeRouteDefinition(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.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CustomRpResourceTypeRouteDefinition(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.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The route definition for a resource implemented by the custom resource provider. + [System.ComponentModel.TypeConverter(typeof(CustomRpResourceTypeRouteDefinitionTypeConverter))] + public partial interface ICustomRpResourceTypeRouteDefinition + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.TypeConverter.cs new file mode 100644 index 000000000000..5a99cae19439 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.TypeConverter.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CustomRpResourceTypeRouteDefinitionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CustomRpResourceTypeRouteDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CustomRpResourceTypeRouteDefinition.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CustomRpResourceTypeRouteDefinition.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/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.cs new file mode 100644 index 000000000000..4e458476a22e --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.cs @@ -0,0 +1,80 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// + /// The route definition for a resource implemented by the custom resource provider. + /// + public partial class CustomRpResourceTypeRouteDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinitionInternal, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition __customRpRouteDefinition = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpRouteDefinition(); + + /// + /// The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of + /// a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Endpoint { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Endpoint; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Endpoint = value; } + + /// + /// The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)__customRpRouteDefinition).Name = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting? _routingType; + + /// The routing types that are supported for resource requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting? RoutingType { get => this._routingType; set => this._routingType = value; } + + /// Creates an new instance. + public CustomRpResourceTypeRouteDefinition() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__customRpRouteDefinition), __customRpRouteDefinition); + await eventListener.AssertObjectIsValid(nameof(__customRpRouteDefinition), __customRpRouteDefinition); + } + } + /// The route definition for a resource implemented by the custom resource provider. + public partial interface ICustomRpResourceTypeRouteDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition + { + /// The routing types that are supported for resource requests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The routing types that are supported for resource requests.", + SerializedName = @"routingType", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting? RoutingType { get; set; } + + } + /// The route definition for a resource implemented by the custom resource provider. + internal partial interface ICustomRpResourceTypeRouteDefinitionInternal : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal + { + /// The routing types that are supported for resource requests. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting? RoutingType { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.json.cs new file mode 100644 index 000000000000..930136ea454e --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpResourceTypeRouteDefinition.json.cs @@ -0,0 +1,106 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// + /// The route definition for a resource implemented by the custom resource provider. + /// + public partial class CustomRpResourceTypeRouteDefinition + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal CustomRpResourceTypeRouteDefinition(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __customRpRouteDefinition = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpRouteDefinition(json); + {_routingType = If( json?.PropertyT("routingType"), out var __jsonRoutingType) ? (string)__jsonRoutingType : (string)RoutingType;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new CustomRpResourceTypeRouteDefinition(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __customRpRouteDefinition?.ToJson(container, serializationMode); + AddIf( null != (((object)this._routingType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._routingType.ToString()) : null, "routingType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.PowerShell.cs new file mode 100644 index 000000000000..e0bd552890be --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A route definition that defines an action or resource that can be interacted with through the custom resource provider. + /// + [System.ComponentModel.TypeConverter(typeof(CustomRpRouteDefinitionTypeConverter))] + public partial class CustomRpRouteDefinition + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CustomRpRouteDefinition(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CustomRpRouteDefinition(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint = (string) content.GetValueForProperty("Endpoint",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal)this).Endpoint, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CustomRpRouteDefinition(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.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CustomRpRouteDefinition(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.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// A route definition that defines an action or resource that can be interacted with through the custom resource provider. + [System.ComponentModel.TypeConverter(typeof(CustomRpRouteDefinitionTypeConverter))] + public partial interface ICustomRpRouteDefinition + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.TypeConverter.cs new file mode 100644 index 000000000000..86e24fa18e5f --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CustomRpRouteDefinitionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CustomRpRouteDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CustomRpRouteDefinition.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CustomRpRouteDefinition.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/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.cs new file mode 100644 index 000000000000..f57f0ece5761 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.cs @@ -0,0 +1,80 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// + /// A route definition that defines an action or resource that can be interacted with through the custom resource provider. + /// + public partial class CustomRpRouteDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinitionInternal + { + + /// Backing field for property. + private string _endpoint; + + /// + /// The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of + /// a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Backing field for property. + private string _name; + + /// + /// The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public CustomRpRouteDefinition() + { + + } + } + /// A route definition that defines an action or resource that can be interacted with through the custom resource provider. + public partial interface ICustomRpRouteDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// + /// The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of + /// a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}')", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + string Endpoint { get; set; } + /// + /// The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}')", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// A route definition that defines an action or resource that can be interacted with through the custom resource provider. + internal partial interface ICustomRpRouteDefinitionInternal + + { + /// + /// The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of + /// a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + /// + string Endpoint { get; set; } + /// + /// The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + /// + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.json.cs new file mode 100644 index 000000000000..94290a65d756 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpRouteDefinition.json.cs @@ -0,0 +1,105 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// + /// A route definition that defines an action or resource that can be interacted with through the custom resource provider. + /// + public partial class CustomRpRouteDefinition + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal CustomRpRouteDefinition(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_endpoint = If( json?.PropertyT("endpoint"), out var __jsonEndpoint) ? (string)__jsonEndpoint : (string)Endpoint;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpRouteDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new CustomRpRouteDefinition(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._endpoint)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._endpoint.ToString()) : null, "endpoint" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.PowerShell.cs new file mode 100644 index 000000000000..16943c6b55a2 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// A validation to apply on custom resource provider requests. + [System.ComponentModel.TypeConverter(typeof(CustomRpValidationsTypeConverter))] + public partial class CustomRpValidations + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CustomRpValidations(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).Specification = (string) content.GetValueForProperty("Specification",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).Specification, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).ValidationType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType?) content.GetValueForProperty("ValidationType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).ValidationType, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType.CreateFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CustomRpValidations(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).Specification = (string) content.GetValueForProperty("Specification",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).Specification, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).ValidationType = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType?) content.GetValueForProperty("ValidationType",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal)this).ValidationType, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType.CreateFrom); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CustomRpValidations(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.CustomProviders.Models.Api20180901Preview.ICustomRpValidations DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CustomRpValidations(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.CustomProviders.Models.Api20180901Preview.ICustomRpValidations FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// A validation to apply on custom resource provider requests. + [System.ComponentModel.TypeConverter(typeof(CustomRpValidationsTypeConverter))] + public partial interface ICustomRpValidations + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.TypeConverter.cs new file mode 100644 index 000000000000..cc48f0135a13 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CustomRpValidationsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CustomRpValidations.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CustomRpValidations.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CustomRpValidations.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/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.cs new file mode 100644 index 000000000000..e5511c21af43 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.cs @@ -0,0 +1,69 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// A validation to apply on custom resource provider requests. + public partial class CustomRpValidations : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidationsInternal + { + + /// Backing field for property. + private string _specification; + + /// + /// A link to the validation specification. The specification must be hosted on raw.githubusercontent.com. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Specification { get => this._specification; set => this._specification = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType? _validationType; + + /// The type of validation to run against a matching request. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType? ValidationType { get => this._validationType; set => this._validationType = value; } + + /// Creates an new instance. + public CustomRpValidations() + { + + } + } + /// A validation to apply on custom resource provider requests. + public partial interface ICustomRpValidations : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// + /// A link to the validation specification. The specification must be hosted on raw.githubusercontent.com. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"A link to the validation specification. The specification must be hosted on raw.githubusercontent.com.", + SerializedName = @"specification", + PossibleTypes = new [] { typeof(string) })] + string Specification { get; set; } + /// The type of validation to run against a matching request. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The type of validation to run against a matching request.", + SerializedName = @"validationType", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType? ValidationType { get; set; } + + } + /// A validation to apply on custom resource provider requests. + internal partial interface ICustomRpValidationsInternal + + { + /// + /// A link to the validation specification. The specification must be hosted on raw.githubusercontent.com. + /// + string Specification { get; set; } + /// The type of validation to run against a matching request. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType? ValidationType { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.json.cs new file mode 100644 index 000000000000..e0e7fd42a21e --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/CustomRpValidations.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// A validation to apply on custom resource provider requests. + public partial class CustomRpValidations + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal CustomRpValidations(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_specification = If( json?.PropertyT("specification"), out var __jsonSpecification) ? (string)__jsonSpecification : (string)Specification;} + {_validationType = If( json?.PropertyT("validationType"), out var __jsonValidationType) ? (string)__jsonValidationType : (string)ValidationType;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new CustomRpValidations(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._specification)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._specification.ToString()) : null, "specification" ,container.Add ); + AddIf( null != (((object)this._validationType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._validationType.ToString()) : null, "validationType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.PowerShell.cs new file mode 100644 index 000000000000..c6a8ca4be716 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// Error definition. + [System.ComponentModel.TypeConverter(typeof(ErrorDefinitionTypeConverter))] + public partial class ErrorDefinition + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDefinition(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.CustomProviders.Models.Api20180901Preview.IErrorDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDefinition(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDefinition(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinitionTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDefinition(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinitionTypeConverter.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.CustomProviders.Models.Api20180901Preview.IErrorDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Error definition. + [System.ComponentModel.TypeConverter(typeof(ErrorDefinitionTypeConverter))] + public partial interface IErrorDefinition + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.TypeConverter.cs new file mode 100644 index 000000000000..68d367fb2379 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDefinitionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDefinition.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDefinition.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/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.cs new file mode 100644 index 000000000000..11eec8c39f04 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.cs @@ -0,0 +1,95 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Error definition. + public partial class ErrorDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal + { + + /// Backing field for property. + private string _code; + + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] _detail; + + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Detail { get => this._detail; } + + /// Backing field for property. + private string _message; + + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal.Message { get => this._message; set { {_message = value;} } } + + /// Creates an new instance. + public ErrorDefinition() + { + + } + } + /// Error definition. + public partial interface IErrorDefinition : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Service specific error code which serves as the substatus for the HTTP error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Internal error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Detail { get; } + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Description of the error.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + + } + /// Error definition. + internal partial interface IErrorDefinitionInternal + + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + string Code { get; set; } + /// Internal error details. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Detail { get; set; } + /// Description of the error. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.json.cs new file mode 100644 index 000000000000..0103d385ab9b --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorDefinition.json.cs @@ -0,0 +1,122 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Error definition. + public partial class ErrorDefinition + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDefinition(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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;} + {_detail = If( json?.PropertyT("details"), out var __jsonDetails) ? If( __jsonDetails as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition) (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinition.FromJson(__u) )) ))() : null : Detail;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ErrorDefinition(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.PowerShell.cs new file mode 100644 index 000000000000..dac77b25ad18 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// Error response. + [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); + + /// + /// 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.CustomProviders.Models.Api20180901Preview.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.CustomProviders.Models.Api20180901Preview.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 + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinitionTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinitionTypeConverter.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 + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinitionTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinitionTypeConverter.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.CustomProviders.Models.Api20180901Preview.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Error response. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.TypeConverter.cs new file mode 100644 index 000000000000..ccce71aa6779 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.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/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.cs new file mode 100644 index 000000000000..6080f7e7b667 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.cs @@ -0,0 +1,98 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Error response. + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal + { + + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Code; } + + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition _error; + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinition()); set => this._error = value; } + + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Code = value; } + + /// Internal Acessors for Detail + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Detail = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ErrorDefinition()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinitionInternal)Error).Message = value; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Error response. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Service specific error code which serves as the substatus for the HTTP error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Internal error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Detail { get; } + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Description of the error.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + + } + /// Error response. + internal partial interface IErrorResponseInternal + + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + string Code { get; set; } + /// Internal error details. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition[] Detail { get; set; } + /// The error details. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorDefinition Error { get; set; } + /// Description of the error. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.json.cs new file mode 100644 index 000000000000..22511dc6f241 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ErrorResponse.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Error response. + 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Models.Api20180901Preview.ErrorDefinition.FromJson(__jsonError) : Error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.PowerShell.cs new file mode 100644 index 000000000000..eba5ab27dbde --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// List of custom resource providers. + [System.ComponentModel.TypeConverter(typeof(ListByCustomRpManifestTypeConverter))] + public partial class ListByCustomRpManifest + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ListByCustomRpManifest(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.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ListByCustomRpManifest(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.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ListByCustomRpManifest(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ListByCustomRpManifest(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifestTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// List of custom resource providers. + [System.ComponentModel.TypeConverter(typeof(ListByCustomRpManifestTypeConverter))] + public partial interface IListByCustomRpManifest + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.TypeConverter.cs new file mode 100644 index 000000000000..249b84e736a1 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ListByCustomRpManifestTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ListByCustomRpManifest.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ListByCustomRpManifest.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ListByCustomRpManifest.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/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.cs new file mode 100644 index 000000000000..584523825318 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// List of custom resource providers. + public partial class ListByCustomRpManifest : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifestInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to use for getting the next set of results. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest[] _value; + + /// The array of custom resource provider manifests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ListByCustomRpManifest() + { + + } + } + /// List of custom resource providers. + public partial interface IListByCustomRpManifest : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// The URL to use for getting the next set of results. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to use for getting the next set of results.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The array of custom resource provider manifests. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The array of custom resource provider manifests.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest[] Value { get; set; } + + } + /// List of custom resource providers. + internal partial interface IListByCustomRpManifestInternal + + { + /// The URL to use for getting the next set of results. + string NextLink { get; set; } + /// The array of custom resource provider manifests. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.json.cs new file mode 100644 index 000000000000..cc4f116f3861 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ListByCustomRpManifest.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// List of custom resource providers. + public partial class ListByCustomRpManifest + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IListByCustomRpManifest FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ListByCustomRpManifest(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal ListByCustomRpManifest(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest) (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifest.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.PowerShell.cs new file mode 100644 index 000000000000..a7569012b96c --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// The resource definition. + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.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.CustomProviders.Models.Api20180901Preview.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.CustomProviders.Models.Api20180901Preview.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTagsTypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTagsTypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The resource definition. + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.TypeConverter.cs new file mode 100644 index 000000000000..610f5d8d068d --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.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/CustomProviders/generated/api/Models/Api20180901Preview/Resource.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.cs new file mode 100644 index 000000000000..4c5fd9ec888e --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.cs @@ -0,0 +1,123 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The resource definition. + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResource, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal + { + + /// Backing field for property. + private string _id; + + /// Resource Id + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Backing field for property. + private string _location; + + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Resource name + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags _tag; + + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags()); set => this._tag = value; } + + /// Backing field for property. + private string _type; + + /// Resource type + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// The resource definition. + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// Resource Id + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource Id", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Resource location", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Resource name + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource name", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags Tag { get; set; } + /// Resource type + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource type", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The resource definition. + internal partial interface IResourceInternal + + { + /// Resource Id + string Id { get; set; } + /// Resource location + string Location { get; set; } + /// Resource name + string Name { get; set; } + /// Resource tags + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags Tag { get; set; } + /// Resource type + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.json.cs new file mode 100644 index 000000000000..dbf47d6b3cc5 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/Resource.json.cs @@ -0,0 +1,118 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The resource definition. + 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.PowerShell.cs new file mode 100644 index 000000000000..3db4cffee498 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.PowerShell.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// Supported operations of this resource provider. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationTypeConverter))] + public partial class ResourceProviderOperation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProviderOperation(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.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProviderOperation(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.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProviderOperation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProviderOperation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Supported operations of this resource provider. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationTypeConverter))] + public partial interface IResourceProviderOperation + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.TypeConverter.cs new file mode 100644 index 000000000000..08e74437f884 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProviderOperationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProviderOperation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProviderOperation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProviderOperation.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/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.cs new file mode 100644 index 000000000000..2aa044cace51 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Supported operations of this resource provider. + public partial class ResourceProviderOperation : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay _display; + + /// Display metadata associated with the operation. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationDisplay()); set => this._display = value; } + + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Description = value; } + + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Operation = value; } + + /// Resource provider: Microsoft Custom Providers. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Provider = value; } + + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationDisplay()); set { {_display = value;} } } + + /// Backing field for property. + private string _name; + + /// Operation name, in format of {provider}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public ResourceProviderOperation() + { + + } + } + /// Supported operations of this resource provider. + public partial interface IResourceProviderOperation : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description of this operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; set; } + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of operation: get, read, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; set; } + /// Resource provider: Microsoft Custom Providers. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource provider: Microsoft Custom Providers.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; set; } + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; set; } + /// Operation name, in format of {provider}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Operation name, in format of {provider}/{resource}/{operation}", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Supported operations of this resource provider. + internal partial interface IResourceProviderOperationInternal + + { + /// Display metadata associated with the operation. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay Display { get; set; } + /// Description of this operation. + string DisplayDescription { get; set; } + /// Type of operation: get, read, delete, etc. + string DisplayOperation { get; set; } + /// Resource provider: Microsoft Custom Providers. + string DisplayProvider { get; set; } + /// Resource on which the operation is performed. + string DisplayResource { get; set; } + /// Operation name, in format of {provider}/{resource}/{operation} + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.json.cs new file mode 100644 index 000000000000..7456c8555eec --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperation.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Supported operations of this resource provider. + public partial class ResourceProviderOperation + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ResourceProviderOperation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceProviderOperation(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationDisplay.FromJson(__jsonDisplay) : Display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.PowerShell.cs new file mode 100644 index 000000000000..197419d9faf7 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// Display metadata associated with the operation. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationDisplayTypeConverter))] + public partial class ResourceProviderOperationDisplay + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProviderOperationDisplay(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.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProviderOperationDisplay(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.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProviderOperationDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProviderOperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Display metadata associated with the operation. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationDisplayTypeConverter))] + public partial interface IResourceProviderOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.TypeConverter.cs new file mode 100644 index 000000000000..186a1ad845d4 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProviderOperationDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProviderOperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProviderOperationDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProviderOperationDisplay.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/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.cs new file mode 100644 index 000000000000..3c98e384bf72 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.cs @@ -0,0 +1,97 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Display metadata associated with the operation. + public partial class ResourceProviderOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _operation; + + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Operation { get => this._operation; set => this._operation = value; } + + /// Backing field for property. + private string _provider; + + /// Resource provider: Microsoft Custom Providers. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Provider { get => this._provider; set => this._provider = value; } + + /// Backing field for property. + private string _resource; + + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Resource { get => this._resource; set => this._resource = value; } + + /// Creates an new instance. + public ResourceProviderOperationDisplay() + { + + } + } + /// Display metadata associated with the operation. + public partial interface IResourceProviderOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description of this operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of operation: get, read, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; set; } + /// Resource provider: Microsoft Custom Providers. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource provider: Microsoft Custom Providers.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; set; } + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; set; } + + } + /// Display metadata associated with the operation. + internal partial interface IResourceProviderOperationDisplayInternal + + { + /// Description of this operation. + string Description { get; set; } + /// Type of operation: get, read, delete, etc. + string Operation { get; set; } + /// Resource provider: Microsoft Custom Providers. + string Provider { get; set; } + /// Resource on which the operation is performed. + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.json.cs new file mode 100644 index 000000000000..10f1c1822b66 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationDisplay.json.cs @@ -0,0 +1,107 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Display metadata associated with the operation. + public partial class ResourceProviderOperationDisplay + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ResourceProviderOperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceProviderOperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)Description;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)Operation;} + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)Provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)Resource;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.PowerShell.cs new file mode 100644 index 000000000000..4c9980445ccd --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// Results of the request to list operations. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationListTypeConverter))] + public partial class ResourceProviderOperationList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProviderOperationList(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.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProviderOperationList(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.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProviderOperationList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProviderOperationList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Results of the request to list operations. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationListTypeConverter))] + public partial interface IResourceProviderOperationList + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.TypeConverter.cs new file mode 100644 index 000000000000..01cf2c80c2e3 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProviderOperationListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProviderOperationList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProviderOperationList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProviderOperationList.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/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.cs new file mode 100644 index 000000000000..c5c3965282fc --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Results of the request to list operations. + public partial class ResourceProviderOperationList : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationListInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to use for getting the next set of results. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation[] _value; + + /// List of operations supported by this resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ResourceProviderOperationList() + { + + } + } + /// Results of the request to list operations. + public partial interface IResourceProviderOperationList : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// The URL to use for getting the next set of results. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to use for getting the next set of results.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// List of operations supported by this resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of operations supported by this resource provider.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation[] Value { get; set; } + + } + /// Results of the request to list operations. + internal partial interface IResourceProviderOperationListInternal + + { + /// The URL to use for getting the next set of results. + string NextLink { get; set; } + /// List of operations supported by this resource provider. + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.json.cs new file mode 100644 index 000000000000..6bc938ccfd7d --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProviderOperationList.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Results of the request to list operations. + public partial class ResourceProviderOperationList + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperationList FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ResourceProviderOperationList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceProviderOperationList(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation) (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProviderOperation.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.PowerShell.cs new file mode 100644 index 000000000000..6cdf1a1e8cd5 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// custom resource provider update information. + [System.ComponentModel.TypeConverter(typeof(ResourceProvidersUpdateTypeConverter))] + public partial class ResourceProvidersUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProvidersUpdate(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.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProvidersUpdate(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.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProvidersUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdateTagsTypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProvidersUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdateTagsTypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// custom resource provider update information. + [System.ComponentModel.TypeConverter(typeof(ResourceProvidersUpdateTypeConverter))] + public partial interface IResourceProvidersUpdate + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.TypeConverter.cs new file mode 100644 index 000000000000..0c75da8d21b9 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProvidersUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProvidersUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProvidersUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProvidersUpdate.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/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.cs new file mode 100644 index 000000000000..da6a03b84505 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// custom resource provider update information. + public partial class ResourceProvidersUpdate : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags _tag; + + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdateTags()); set => this._tag = value; } + + /// Creates an new instance. + public ResourceProvidersUpdate() + { + + } + } + /// custom resource provider update information. + public partial interface IResourceProvidersUpdate : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags) })] + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags Tag { get; set; } + + } + /// custom resource provider update information. + internal partial interface IResourceProvidersUpdateInternal + + { + /// Resource tags + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.json.cs new file mode 100644 index 000000000000..f966407bb677 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdate.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// custom resource provider update information. + public partial class ResourceProvidersUpdate + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ResourceProvidersUpdate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceProvidersUpdate(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdateTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.PowerShell.cs new file mode 100644 index 000000000000..d21956b422cd --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(ResourceProvidersUpdateTagsTypeConverter))] + public partial class ResourceProvidersUpdateTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProvidersUpdateTags(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.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProvidersUpdateTags(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.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProvidersUpdateTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProvidersUpdateTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(ResourceProvidersUpdateTagsTypeConverter))] + public partial interface IResourceProvidersUpdateTags + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.TypeConverter.cs new file mode 100644 index 000000000000..31befb7621d3 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProvidersUpdateTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProvidersUpdateTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProvidersUpdateTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProvidersUpdateTags.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/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.cs new file mode 100644 index 000000000000..01dffa07e887 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Resource tags + public partial class ResourceProvidersUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTagsInternal + { + + /// Creates an new instance. + public ResourceProvidersUpdateTags() + { + + } + } + /// Resource tags + public partial interface IResourceProvidersUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray + { + + } + /// Resource tags + internal partial interface IResourceProvidersUpdateTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.dictionary.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.dictionary.cs new file mode 100644 index 000000000000..438fbd5102dc --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + public partial class ResourceProvidersUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdateTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.json.cs new file mode 100644 index 000000000000..d0a62fbb9a52 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceProvidersUpdateTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Resource tags + public partial class ResourceProvidersUpdateTags + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ResourceProvidersUpdateTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ResourceProvidersUpdateTags(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.PowerShell.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.PowerShell.cs new file mode 100644 index 000000000000..581cd7ece989 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(ResourceTagsTypeConverter))] + public partial class ResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(ResourceTagsTypeConverter))] + public partial interface IResourceTags + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.TypeConverter.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.TypeConverter.cs new file mode 100644 index 000000000000..3eecad39fe67 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.cs new file mode 100644 index 000000000000..9a4ad4a276c3 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Resource tags + public partial class ResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTagsInternal + { + + /// Creates an new instance. + public ResourceTags() + { + + } + } + /// Resource tags + public partial interface IResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray + { + + } + /// Resource tags + internal partial interface IResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.dictionary.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.dictionary.cs new file mode 100644 index 000000000000..99352c657138 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + public partial class ResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.json.cs b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.json.cs new file mode 100644 index 000000000000..88387145eef1 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/Api20180901Preview/ResourceTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Resource tags + public partial class ResourceTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new ResourceTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ResourceTags(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.PowerShell.cs b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.PowerShell.cs new file mode 100644 index 000000000000..8c146875b25d --- /dev/null +++ b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.PowerShell.cs @@ -0,0 +1,144 @@ +// 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.CustomProviders.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(CustomProvidersIdentityTypeConverter))] + public partial class CustomProvidersIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CustomProvidersIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).AssociationName = (string) content.GetValueForProperty("AssociationName",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).AssociationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceProviderName = (string) content.GetValueForProperty("ResourceProviderName",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceProviderName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Scope = (string) content.GetValueForProperty("Scope",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Scope, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CustomProvidersIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).AssociationName = (string) content.GetValueForProperty("AssociationName",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).AssociationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceProviderName = (string) content.GetValueForProperty("ResourceProviderName",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).ResourceProviderName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Scope = (string) content.GetValueForProperty("Scope",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).Scope, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CustomProvidersIdentity(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.CustomProviders.Models.ICustomProvidersIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CustomProvidersIdentity(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.CustomProviders.Models.ICustomProvidersIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(CustomProvidersIdentityTypeConverter))] + public partial interface ICustomProvidersIdentity + + { + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.TypeConverter.cs b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.TypeConverter.cs new file mode 100644 index 000000000000..c51afe552e30 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.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.CustomProviders.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CustomProvidersIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity 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 CustomProvidersIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CustomProvidersIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CustomProvidersIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CustomProvidersIdentity.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/CustomProviders/generated/api/Models/CustomProvidersIdentity.cs b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.cs new file mode 100644 index 000000000000..cfb0d3ecb907 --- /dev/null +++ b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.cs @@ -0,0 +1,139 @@ +// 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.CustomProviders.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + public partial class CustomProvidersIdentity : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentityInternal + { + + /// Backing field for property. + private string _associationName; + + /// The name of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string AssociationName { get => this._associationName; set => this._associationName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceProviderName; + + /// The name of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string ResourceProviderName { get => this._resourceProviderName; set => this._resourceProviderName = value; } + + /// Backing field for property. + private string _scope; + + /// The scope of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string Scope { get => this._scope; set => this._scope = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Origin(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public CustomProvidersIdentity() + { + + } + } + public partial interface ICustomProvidersIdentity : + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IJsonSerializable + { + /// The name of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the association.", + SerializedName = @"associationName", + PossibleTypes = new [] { typeof(string) })] + string AssociationName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The name of the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroupName { get; set; } + /// The name of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the resource provider.", + SerializedName = @"resourceProviderName", + PossibleTypes = new [] { typeof(string) })] + string ResourceProviderName { get; set; } + /// The scope of the association. + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The scope of the association.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + string Scope { get; set; } + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface ICustomProvidersIdentityInternal + + { + /// The name of the association. + string AssociationName { get; set; } + /// Resource identity path + string Id { get; set; } + /// The name of the resource group. + string ResourceGroupName { get; set; } + /// The name of the resource provider. + string ResourceProviderName { get; set; } + /// The scope of the association. + string Scope { get; set; } + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.json.cs b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.json.cs new file mode 100644 index 000000000000..6756e2e48ffc --- /dev/null +++ b/src/CustomProviders/generated/api/Models/CustomProvidersIdentity.json.cs @@ -0,0 +1,115 @@ +// 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.CustomProviders.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + public partial class CustomProvidersIdentity + { + + /// + /// 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.CustomProviders.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject instance to deserialize from. + internal CustomProvidersIdentity(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_associationName = If( json?.PropertyT("associationName"), out var __jsonAssociationName) ? (string)__jsonAssociationName : (string)AssociationName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)ResourceGroupName;} + {_resourceProviderName = If( json?.PropertyT("resourceProviderName"), out var __jsonResourceProviderName) ? (string)__jsonResourceProviderName : (string)ResourceProviderName;} + {_scope = If( json?.PropertyT("scope"), out var __jsonScope) ? (string)__jsonScope : (string)Scope;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)SubscriptionId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject json ? new CustomProvidersIdentity(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.CustomProviders.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._associationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._associationName.ToString()) : null, "associationName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._resourceProviderName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._resourceProviderName.ToString()) : null, "resourceProviderName" ,container.Add ); + AddIf( null != (((object)this._scope)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._scope.ToString()) : null, "scope" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ActionRouting.Completer.cs b/src/CustomProviders/generated/api/Support/ActionRouting.Completer.cs new file mode 100644 index 000000000000..433db6ef64a0 --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ActionRouting.Completer.cs @@ -0,0 +1,35 @@ +// 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.CustomProviders.Support +{ + + /// Argument completer implementation for ActionRouting. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRoutingTypeConverter))] + public partial struct ActionRouting : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Proxy".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Proxy", "Proxy", global::System.Management.Automation.CompletionResultType.ParameterValue, "Proxy"); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ActionRouting.TypeConverter.cs b/src/CustomProviders/generated/api/Support/ActionRouting.TypeConverter.cs new file mode 100644 index 000000000000..efa6022ed5c8 --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ActionRouting.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support +{ + + /// TypeConverter implementation for ActionRouting. + public partial class ActionRoutingTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ActionRouting.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ActionRouting.cs b/src/CustomProviders/generated/api/Support/ActionRouting.cs new file mode 100644 index 000000000000..c601319c269f --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ActionRouting.cs @@ -0,0 +1,95 @@ +// 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.CustomProviders.Support +{ + + public partial struct ActionRouting : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting Proxy = @"Proxy"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Creates an instance of the + /// the value to create an instance for. + private ActionRouting(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Conversion from arbitrary object to ActionRouting + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ActionRouting(System.Convert.ToString(value)); + } + + /// Compares values of enum type ActionRouting + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ActionRouting (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ActionRouting && Equals((ActionRouting)obj); + } + + /// Returns hashCode for enum ActionRouting + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Returns string representation for ActionRouting + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ActionRouting + /// the value to convert to an instance of . + + public static implicit operator ActionRouting(string value) + { + return new ActionRouting(value); + } + + /// Implicit operator to convert ActionRouting to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting e) + { + return e._value; + } + + /// Overriding != operator for enum ActionRouting + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ActionRouting + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ActionRouting e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ProvisioningState.Completer.cs b/src/CustomProviders/generated/api/Support/ProvisioningState.Completer.cs new file mode 100644 index 000000000000..18d921a10d7f --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ProvisioningState.Completer.cs @@ -0,0 +1,51 @@ +// 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.CustomProviders.Support +{ + + /// Argument completer implementation for ProvisioningState. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningStateTypeConverter))] + public partial struct ProvisioningState : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Accepted".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Accepted", "Accepted", global::System.Management.Automation.CompletionResultType.ParameterValue, "Accepted"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Deleting".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Deleting", "Deleting", global::System.Management.Automation.CompletionResultType.ParameterValue, "Deleting"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Running".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Running", "Running", global::System.Management.Automation.CompletionResultType.ParameterValue, "Running"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Succeeded".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Succeeded", "Succeeded", global::System.Management.Automation.CompletionResultType.ParameterValue, "Succeeded"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Failed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Failed", "Failed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Failed"); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ProvisioningState.TypeConverter.cs b/src/CustomProviders/generated/api/Support/ProvisioningState.TypeConverter.cs new file mode 100644 index 000000000000..9ddd99defabe --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ProvisioningState.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support +{ + + /// TypeConverter implementation for ProvisioningState. + public partial class ProvisioningStateTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ProvisioningState.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ProvisioningState.cs b/src/CustomProviders/generated/api/Support/ProvisioningState.cs new file mode 100644 index 000000000000..ce113ee805c7 --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ProvisioningState.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. +// 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.CustomProviders.Support +{ + + public partial struct ProvisioningState : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState Accepted = @"Accepted"; + + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState Deleting = @"Deleting"; + + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState Failed = @"Failed"; + + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState Running = @"Running"; + + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState Succeeded = @"Succeeded"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to ProvisioningState + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ProvisioningState(System.Convert.ToString(value)); + } + + /// Compares values of enum type ProvisioningState + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ProvisioningState (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ProvisioningState && Equals((ProvisioningState)obj); + } + + /// Returns hashCode for enum ProvisioningState + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private ProvisioningState(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for ProvisioningState + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ProvisioningState + /// the value to convert to an instance of . + + public static implicit operator ProvisioningState(string value) + { + return new ProvisioningState(value); + } + + /// Implicit operator to convert ProvisioningState to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState e) + { + return e._value; + } + + /// Overriding != operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ProvisioningState e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ResourceTypeRouting.Completer.cs b/src/CustomProviders/generated/api/Support/ResourceTypeRouting.Completer.cs new file mode 100644 index 000000000000..2edb1bf376df --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ResourceTypeRouting.Completer.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. +// 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.CustomProviders.Support +{ + + /// Argument completer implementation for ResourceTypeRouting. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRoutingTypeConverter))] + public partial struct ResourceTypeRouting : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Proxy".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Proxy", "Proxy", global::System.Management.Automation.CompletionResultType.ParameterValue, "Proxy"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Proxy,Cache".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Proxy,Cache", "Proxy,Cache", global::System.Management.Automation.CompletionResultType.ParameterValue, "Proxy,Cache"); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ResourceTypeRouting.TypeConverter.cs b/src/CustomProviders/generated/api/Support/ResourceTypeRouting.TypeConverter.cs new file mode 100644 index 000000000000..5408646a1581 --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ResourceTypeRouting.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support +{ + + /// TypeConverter implementation for ResourceTypeRouting. + public partial class ResourceTypeRoutingTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ResourceTypeRouting.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ResourceTypeRouting.cs b/src/CustomProviders/generated/api/Support/ResourceTypeRouting.cs new file mode 100644 index 000000000000..f4d1aff97944 --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ResourceTypeRouting.cs @@ -0,0 +1,97 @@ +// 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.CustomProviders.Support +{ + + public partial struct ResourceTypeRouting : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting Proxy = @"Proxy"; + + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting ProxyCache = @"Proxy,Cache"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to ResourceTypeRouting + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ResourceTypeRouting(System.Convert.ToString(value)); + } + + /// Compares values of enum type ResourceTypeRouting + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ResourceTypeRouting (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ResourceTypeRouting && Equals((ResourceTypeRouting)obj); + } + + /// Returns hashCode for enum ResourceTypeRouting + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private ResourceTypeRouting(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for ResourceTypeRouting + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ResourceTypeRouting + /// the value to convert to an instance of . + + public static implicit operator ResourceTypeRouting(string value) + { + return new ResourceTypeRouting(value); + } + + /// Implicit operator to convert ResourceTypeRouting to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting e) + { + return e._value; + } + + /// Overriding != operator for enum ResourceTypeRouting + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ResourceTypeRouting + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ResourceTypeRouting e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ValidationType.Completer.cs b/src/CustomProviders/generated/api/Support/ValidationType.Completer.cs new file mode 100644 index 000000000000..3ef5c1d06def --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ValidationType.Completer.cs @@ -0,0 +1,35 @@ +// 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.CustomProviders.Support +{ + + /// Argument completer implementation for ValidationType. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationTypeTypeConverter))] + public partial struct ValidationType : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Swagger".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Swagger", "Swagger", global::System.Management.Automation.CompletionResultType.ParameterValue, "Swagger"); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ValidationType.TypeConverter.cs b/src/CustomProviders/generated/api/Support/ValidationType.TypeConverter.cs new file mode 100644 index 000000000000..314e4f548870 --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ValidationType.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support +{ + + /// TypeConverter implementation for ValidationType. + public partial class ValidationTypeTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ValidationType.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/api/Support/ValidationType.cs b/src/CustomProviders/generated/api/Support/ValidationType.cs new file mode 100644 index 000000000000..a4e04920a6ff --- /dev/null +++ b/src/CustomProviders/generated/api/Support/ValidationType.cs @@ -0,0 +1,95 @@ +// 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.CustomProviders.Support +{ + + public partial struct ValidationType : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType Swagger = @"Swagger"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to ValidationType + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ValidationType(System.Convert.ToString(value)); + } + + /// Compares values of enum type ValidationType + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ValidationType (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ValidationType && Equals((ValidationType)obj); + } + + /// Returns hashCode for enum ValidationType + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Returns string representation for ValidationType + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Creates an instance of the + /// the value to create an instance for. + private ValidationType(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Implicit operator to convert string to ValidationType + /// the value to convert to an instance of . + + public static implicit operator ValidationType(string value) + { + return new ValidationType(value); + } + + /// Implicit operator to convert ValidationType to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType e) + { + return e._value; + } + + /// Overriding != operator for enum ValidationType + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ValidationType + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType e1, Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support.ValidationType e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_Get.cs b/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_Get.cs new file mode 100644 index 000000000000..bad678be1700 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_Get.cs @@ -0,0 +1,378 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Get an association. + /// + /// [OpenAPI] Associations_Get=>GET:"/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCustomProviderAssociation_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Get an association.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzCustomProviderAssociation_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the association. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the association.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the association.", + SerializedName = @"associationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AssociationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _scope; + + /// The scope of the association. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The scope of the association.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The scope of the association.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzCustomProviderAssociation_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.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AssociationsGet(Scope, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_GetViaIdentity.cs b/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_GetViaIdentity.cs new file mode 100644 index 000000000000..8f640b7b5e7b --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_GetViaIdentity.cs @@ -0,0 +1,373 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Get an association. + /// + /// [OpenAPI] Associations_Get=>GET:"/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCustomProviderAssociation_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Get an association.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzCustomProviderAssociation_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzCustomProviderAssociation_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.AssociationsGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Scope) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Scope"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.AssociationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AssociationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.AssociationsGet(InputObject.Scope ?? null, InputObject.AssociationName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_List.cs b/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_List.cs new file mode 100644 index 000000000000..c4c1550db06c --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzCustomProviderAssociation_List.cs @@ -0,0 +1,374 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Gets all association for the given scope. + /// + /// [OpenAPI] Associations_ListAll=>GET:"/{scope}/providers/Microsoft.CustomProviders/associations" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCustomProviderAssociation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Gets all association for the given scope.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzCustomProviderAssociation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _scope; + + /// The scope of the association. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The scope of the association.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The scope of the association.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzCustomProviderAssociation_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.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AssociationsListAll(Scope, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope }) + { + 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 { Scope=Scope }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AssociationsListAll_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_Get.cs b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_Get.cs new file mode 100644 index 000000000000..ff191299f07e --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_Get.cs @@ -0,0 +1,401 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Gets the custom resource provider manifest. + /// + /// [OpenAPI] CustomResourceProvider_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCustomProvider_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Gets the custom resource provider manifest.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzCustomProvider_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the resource provider. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource provider.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource provider.", + SerializedName = @"resourceProviderName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ResourceProviderName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzCustomProvider_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.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_GetViaIdentity.cs b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_GetViaIdentity.cs new file mode 100644 index 000000000000..4a284437b13a --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_GetViaIdentity.cs @@ -0,0 +1,377 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Gets the custom resource provider manifest. + /// + /// [OpenAPI] CustomResourceProvider_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCustomProvider_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Gets the custom resource provider manifest.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzCustomProvider_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzCustomProvider_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CustomResourceProviderGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceProviderName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceProviderName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CustomResourceProviderGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ResourceProviderName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_List.cs b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_List.cs new file mode 100644 index 000000000000..da395216ec60 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_List.cs @@ -0,0 +1,397 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Gets all the custom resource providers within a resource group. + /// + /// [OpenAPI] CustomResourceProvider_ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCustomProvider_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Gets all the custom resource providers within a resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzCustomProvider_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzCustomProvider_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.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_List1.cs b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_List1.cs new file mode 100644 index 000000000000..1bc8ddb79db9 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzCustomProvider_List1.cs @@ -0,0 +1,383 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Gets all the custom resource providers within a subscription. + /// + /// [OpenAPI] CustomResourceProvider_ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.CustomProviders/resourceProviders" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCustomProvider_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Gets all the custom resource providers within a subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzCustomProvider_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzCustomProvider_List1() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/GetAzOperation_List.cs b/src/CustomProviders/generated/cmdlets/GetAzOperation_List.cs new file mode 100644 index 000000000000..2b4abe21b0f3 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/GetAzOperation_List.cs @@ -0,0 +1,361 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// The list of operations provided by Microsoft CustomProviders. + /// + /// [OpenAPI] Operations_List=>GET:"/providers/Microsoft.CustomProviders/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"The list of operations provided by Microsoft CustomProviders.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class GetAzOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzOperation_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.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/cmdlets/NewAzCustomProviderAssociation_CreateExpanded.cs b/src/CustomProviders/generated/cmdlets/NewAzCustomProviderAssociation_CreateExpanded.cs new file mode 100644 index 000000000000..ab1e76b3ce83 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/NewAzCustomProviderAssociation_CreateExpanded.cs @@ -0,0 +1,467 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Create or update an association. + /// + /// [OpenAPI] Associations_CreateOrUpdate=>PUT:"/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCustomProviderAssociation_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Create or update an association.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class NewAzCustomProviderAssociation_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation _associationBody= new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.Association(); + + /// The resource definition of this association. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation AssociationBody { get => this._associationBody; set => this._associationBody = value; } + + /// 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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the association. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the association.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the association.", + SerializedName = @"associationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AssociationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _scope; + + /// + /// The scope of the association. The scope can be any valid REST resource instance. For example, use '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' + /// for a virtual machine resource. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The scope of the association. The scope can be any valid REST resource instance. For example, use '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' for a virtual machine resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The scope of the association. The scope can be any valid REST resource instance. For example, use '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' for a virtual machine resource.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Scope { get => this._scope; set => this._scope = value; } + + /// The REST resource instance of the target resource for this association. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The REST resource instance of the target resource for this association.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The REST resource instance of the target resource for this association.", + SerializedName = @"targetResourceId", + PossibleTypes = new [] { typeof(string) })] + public string TargetResourceId { get => AssociationBody.TargetResourceId ?? null; set => AssociationBody.TargetResourceId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCustomProviderAssociation_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets.NewAzCustomProviderAssociation_CreateExpanded Clone() + { + var clone = new NewAzCustomProviderAssociation_CreateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.AssociationBody = this.AssociationBody; + clone.Scope = this.Scope; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzCustomProviderAssociation_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AssociationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AssociationsCreateOrUpdate(Scope, Name, AssociationBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope,Name=Name,body=AssociationBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope, Name=Name, body=AssociationBody }) + { + 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 { Scope=Scope, Name=Name, body=AssociationBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/NewAzCustomProvider_CreateExpanded.cs b/src/CustomProviders/generated/cmdlets/NewAzCustomProvider_CreateExpanded.cs new file mode 100644 index 000000000000..4db6b973fc34 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/NewAzCustomProvider_CreateExpanded.cs @@ -0,0 +1,533 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Creates or updates the custom resource provider. + /// + /// [OpenAPI] CustomResourceProvider_CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCustomProvider_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Creates or updates the custom resource provider.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class NewAzCustomProvider_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A list of actions that the custom resource provider implements. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A list of actions that the custom resource provider implements.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of actions that the custom resource provider implements.", + SerializedName = @"actions", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition) })] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] Action { get => ResourceProviderBody.Action ?? null /* arrayOf */; set => ResourceProviderBody.Action = value; } + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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; } } + + /// Resource location + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Resource location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Resource location", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ResourceProviderBody.Location ?? null; set => ResourceProviderBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the resource provider. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource provider.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource provider.", + SerializedName = @"resourceProviderName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ResourceProviderName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest _resourceProviderBody= new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.CustomRpManifest(); + + /// A manifest file that defines the custom resource provider resources. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest ResourceProviderBody { get => this._resourceProviderBody; set => this._resourceProviderBody = value; } + + /// A list of resource types that the custom resource provider implements. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A list of resource types that the custom resource provider implements.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of resource types that the custom resource provider implements.", + SerializedName = @"resourceTypes", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition) })] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] ResourceType { get => ResourceProviderBody.ResourceType ?? null /* arrayOf */; set => ResourceProviderBody.ResourceType = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceTags Tag { get => ResourceProviderBody.Tag ?? null /* object */; set => ResourceProviderBody.Tag = value; } + + /// A list of validations to run on the custom resource provider's requests. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A list of validations to run on the custom resource provider's requests.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of validations to run on the custom resource provider's requests.", + SerializedName = @"validations", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations) })] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] Validation { get => ResourceProviderBody.Validation ?? null /* arrayOf */; set => ResourceProviderBody.Validation = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCustomProvider_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets.NewAzCustomProvider_CreateExpanded Clone() + { + var clone = new NewAzCustomProvider_CreateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ResourceProviderBody = this.ResourceProviderBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzCustomProvider_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CustomResourceProviderCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, ResourceProviderBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=ResourceProviderBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ResourceProviderBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ResourceProviderBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/RemoveAzCustomProviderAssociation_Delete.cs b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProviderAssociation_Delete.cs new file mode 100644 index 000000000000..af91cefa6879 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProviderAssociation_Delete.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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Delete an association. + /// + /// [OpenAPI] Associations_Delete=>DELETE:"/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCustomProviderAssociation_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Delete an association.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class RemoveAzCustomProviderAssociation_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the association. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the association.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the association.", + SerializedName = @"associationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("AssociationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _scope; + + /// The scope of the association. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The scope of the association.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The scope of the association.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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 from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCustomProviderAssociation_Delete + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets.RemoveAzCustomProviderAssociation_Delete Clone() + { + var clone = new RemoveAzCustomProviderAssociation_Delete(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.Scope = this.Scope; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AssociationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.AssociationsDelete(Scope, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzCustomProviderAssociation_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Scope=Scope, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/RemoveAzCustomProviderAssociation_DeleteViaIdentity.cs b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProviderAssociation_DeleteViaIdentity.cs new file mode 100644 index 000000000000..9ad2fe8513d1 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProviderAssociation_DeleteViaIdentity.cs @@ -0,0 +1,478 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Delete an association. + /// + /// [OpenAPI] Associations_Delete=>DELETE:"/{scope}/providers/Microsoft.CustomProviders/associations/{associationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCustomProviderAssociation_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Delete an association.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class RemoveAzCustomProviderAssociation_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCustomProviderAssociation_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets.RemoveAzCustomProviderAssociation_DeleteViaIdentity Clone() + { + var clone = new RemoveAzCustomProviderAssociation_DeleteViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'AssociationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.AssociationsDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Scope) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Scope"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.AssociationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AssociationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.AssociationsDelete(InputObject.Scope ?? null, InputObject.AssociationName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzCustomProviderAssociation_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/RemoveAzCustomProvider_Delete.cs b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProvider_Delete.cs new file mode 100644 index 000000000000..4614429d4867 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProvider_Delete.cs @@ -0,0 +1,506 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Deletes the custom resource provider. + /// + /// [OpenAPI] CustomResourceProvider_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCustomProvider_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Deletes the custom resource provider.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class RemoveAzCustomProvider_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the resource provider. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource provider.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource provider.", + SerializedName = @"resourceProviderName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ResourceProviderName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCustomProvider_Delete + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets.RemoveAzCustomProvider_Delete Clone() + { + var clone = new RemoveAzCustomProvider_Delete(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CustomResourceProviderDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderDelete(SubscriptionId, ResourceGroupName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzCustomProvider_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/RemoveAzCustomProvider_DeleteViaIdentity.cs b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProvider_DeleteViaIdentity.cs new file mode 100644 index 000000000000..e69d7438bdc4 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/RemoveAzCustomProvider_DeleteViaIdentity.cs @@ -0,0 +1,482 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// Deletes the custom resource provider. + /// + /// [OpenAPI] CustomResourceProvider_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCustomProvider_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Deletes the custom resource provider.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class RemoveAzCustomProvider_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCustomProvider_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Cmdlets.RemoveAzCustomProvider_DeleteViaIdentity Clone() + { + var clone = new RemoveAzCustomProvider_DeleteViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CustomResourceProviderDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CustomResourceProviderDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceProviderName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceProviderName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CustomResourceProviderDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ResourceProviderName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzCustomProvider_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/UpdateAzCustomProvider_UpdateExpanded.cs b/src/CustomProviders/generated/cmdlets/UpdateAzCustomProvider_UpdateExpanded.cs new file mode 100644 index 000000000000..9d13430c8497 --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/UpdateAzCustomProvider_UpdateExpanded.cs @@ -0,0 +1,421 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// + /// Updates an existing custom resource provider. The only value that can be updated via PATCH currently is the tags. + /// + /// + /// [OpenAPI] CustomResourceProvider_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCustomProvider_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Updates an existing custom resource provider. The only value that can be updated via PATCH currently is the tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class UpdateAzCustomProvider_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// The name of the resource provider. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource provider.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource provider.", + SerializedName = @"resourceProviderName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ResourceProviderName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate _patchableResourceBody= new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdate(); + + /// custom resource provider update information. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate PatchableResourceBody { get => this._patchableResourceBody; set => this._patchableResourceBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags Tag { get => PatchableResourceBody.Tag ?? null /* object */; set => PatchableResourceBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CustomResourceProviderUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CustomResourceProviderUpdate(SubscriptionId, ResourceGroupName, Name, PatchableResourceBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=PatchableResourceBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzCustomProvider_UpdateExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=PatchableResourceBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=PatchableResourceBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/cmdlets/UpdateAzCustomProvider_UpdateViaIdentityExpanded.cs b/src/CustomProviders/generated/cmdlets/UpdateAzCustomProvider_UpdateViaIdentityExpanded.cs new file mode 100644 index 000000000000..ddc6da0d381c --- /dev/null +++ b/src/CustomProviders/generated/cmdlets/UpdateAzCustomProvider_UpdateViaIdentityExpanded.cs @@ -0,0 +1,400 @@ +// 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.CustomProviders.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Extensions; + + /// + /// Updates an existing custom resource provider. The only value that can be updated via PATCH currently is the tags. + /// + /// + /// [OpenAPI] CustomResourceProvider_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCustomProvider_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Description(@"Updates an existing custom resource provider. The only value that can be updated via PATCH currently is the tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Generated] + public partial class UpdateAzCustomProvider_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.CustomProviders Client => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate _patchableResourceBody= new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceProvidersUpdate(); + + /// custom resource provider update information. + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdate PatchableResourceBody { get => this._patchableResourceBody; set => this._patchableResourceBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProvidersUpdateTags Tag { get => PatchableResourceBody.Tag ?? null /* object */; set => PatchableResourceBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CustomResourceProviderUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CustomResourceProviderUpdateViaIdentity(InputObject.Id, PatchableResourceBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceProviderName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceProviderName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CustomResourceProviderUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ResourceProviderName ?? null, PatchableResourceBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=PatchableResourceBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzCustomProvider_UpdateViaIdentityExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=PatchableResourceBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=PatchableResourceBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/AsyncCommandRuntime.cs b/src/CustomProviders/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 000000000000..d8e3d13cd193 --- /dev/null +++ b/src/CustomProviders/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,828 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/runtime/AsyncJob.cs b/src/CustomProviders/generated/runtime/AsyncJob.cs new file mode 100644 index 000000000000..d0d1453db69e --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/AsyncOperationResponse.cs b/src/CustomProviders/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 000000000000..6080292b819a --- /dev/null +++ b/src/CustomProviders/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 000000000000..ae04d7034f9d --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 000000000000..57e3d2dac5b7 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 000000000000..a75b44973b5e --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,99 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support"; + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!IsAzure || pf.Property.Name != "Id") + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = viewParameters.Type.FullName + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 000000000000..68980e725a0c --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 000000000000..aa3a2f81b336 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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.CustomProviders.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Support"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 000000000000..274530931948 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + protected override void ProcessRecord() + { + try { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append(@" +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +"); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder); + } + } + } catch (Exception ee) { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 000000000000..06b3f35780ce --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.0"); + // 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.CustomProviders.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: Custom Providers cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.CustomProviders.private.dll"}'"); + + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.CustomProviders.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = {previewVersion}"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule CustomProviders".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/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 000000000000..82e453244653 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine(@"$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath)" +); + sb.AppendLine($@"$TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@"$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName +"); + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 000000000000..56a0f72d2c40 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 000000000000..d22cbbb38613 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 000000000000..25cdd33adcd6 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/CollectionExtensions.cs b/src/CustomProviders/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 000000000000..26d029bdbee6 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/BuildTime/MarkdownRenderer.cs b/src/CustomProviders/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 000000000000..d8dcb8ede9a9 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + if (markdownInfo.SupportsPaging) + { + foreach (var parameter in SupportsPagingParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"### {alias}{Environment.NewLine}{Environment.NewLine}"); + } + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"{relatedLink}{Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/src/CustomProviders/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 000000000000..6eb5fe2e67d9 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/src/CustomProviders/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 000000000000..3efc90f44039 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() => $@"{ExampleNameHeader}{ExampleInfo.Name} +{ExampleCodeHeader} +{ExampleInfo.Code} +{ExampleCodeFooter} + +{ExampleInfo.Description.ToDescriptionFormat()} + +"; + } + + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Description.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/src/CustomProviders/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 000000000000..b73c6dd71203 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/src/CustomProviders/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 000000000000..5b99616f96e8 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,291 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public string[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + RelatedLinks = commentInfo.RelatedLinks; + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (codeEndIndex ?? 0) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + if (Variant.SupportsPaging) + { + parameterStrings = parameterStrings.Append(" [-First ]").Append(" [-IncludeTotalCount]").Append(" [-Skip ]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string description) + { + Name = name; + Code = code; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}") + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/src/CustomProviders/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 000000000000..eba6fd207104 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,513 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BeginOutput + { + public VariantGroup VariantGroup { get; } + + public BeginOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}')) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + return sb.ToString(); + } + } + + internal class ProcessOutput + { + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + } + + internal class EndOutput + { + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new [] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new []{"
", "\r\n", "\n"}); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => new ArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, !isFirst && includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/src/CustomProviders/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 000000000000..1190507836e0 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,499 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}To construct, see NOTES section for {complexParameterName} properties and create a hash table."; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines().Replace(complexMessage, String.Empty).Replace(complexMessage.ToPsSingleLine(), String.Empty); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[]{} : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + + private const string HelpLinkPrefix = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{variantGroup.ModuleName.ToLowerInvariant()}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => !ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)); + } + return parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))).ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/PsAttributes.cs b/src/CustomProviders/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 000000000000..a1896ccc1e1b --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/PsExtensions.cs b/src/CustomProviders/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 000000000000..bf9781585812 --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal static class PsExtensions + { + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/PsHelpers.cs b/src/CustomProviders/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 000000000000..e70559fbb76f --- /dev/null +++ b/src/CustomProviders/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path '{scriptFolder}' -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.StartsWith(GuidStart))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/src/CustomProviders/generated/runtime/BuildTime/StringExtensions.cs b/src/CustomProviders/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 000000000000..2bcec7e0207f --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/BuildTime/XmlExtensions.cs b/src/CustomProviders/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 000000000000..deba832243dc --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/CmdInfoHandler.cs b/src/CustomProviders/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 000000000000..f6fb2bf579ee --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/ConversionException.cs b/src/CustomProviders/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 000000000000..6ce7a277e4ca --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/IJsonConverter.cs b/src/CustomProviders/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 000000000000..69987165cb2e --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Conversions/Instances/BinaryConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 000000000000..9ad6adc9aecd --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/BooleanConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 000000000000..60d18613a0ba --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 000000000000..6f4f1469733f --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 000000000000..3b62f0a9312b --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/DecimalConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 000000000000..78d8d9044eab --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/DoubleConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 000000000000..29b7850b9a30 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/EnumConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 000000000000..44d12578fd28 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/GuidConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 000000000000..6320d30bd783 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 000000000000..f362d3d3ad8e --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/Int16Converter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 000000000000..a3dc4bf1f2ab --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/Int32Converter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 000000000000..1c3ac83baf2d --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/Int64Converter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 000000000000..751e6ef95dc1 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 000000000000..f9b718c0eaf6 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 000000000000..19c1b74d5048 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/SingleConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 000000000000..688aadb84eee --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/StringConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 000000000000..ff1140e15078 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 000000000000..64d8f763c4f4 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/UInt16Converter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 000000000000..60007f2d2a47 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/UInt32Converter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 000000000000..28b86a02b0e9 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/UInt64Converter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 000000000000..dedee2199298 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/Instances/UriConverter.cs b/src/CustomProviders/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 000000000000..01633120015a --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/JsonConverter.cs b/src/CustomProviders/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 000000000000..9de0a712a643 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/JsonConverterAttribute.cs b/src/CustomProviders/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 000000000000..79aae7833d51 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/JsonConverterFactory.cs b/src/CustomProviders/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 000000000000..9a3470a409eb --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Conversions/StringLikeConverter.cs b/src/CustomProviders/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 000000000000..7c0623db1b7e --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Customizations/IJsonSerializable.cs b/src/CustomProviders/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 000000000000..677eefbdfdb5 --- /dev/null +++ b/src/CustomProviders/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Customizations/JsonArray.cs b/src/CustomProviders/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 000000000000..ea01c3dd4bba --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Customizations/JsonBoolean.cs b/src/CustomProviders/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 000000000000..af3465654c8e --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Customizations/JsonNode.cs b/src/CustomProviders/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 000000000000..7d1f7933ee4b --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Customizations/JsonNumber.cs b/src/CustomProviders/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 000000000000..6dd3c63a40cf --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Customizations/JsonObject.cs b/src/CustomProviders/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 000000000000..c16274229cd4 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/runtime/Customizations/JsonString.cs b/src/CustomProviders/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 000000000000..1384ce8ac20b --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Customizations/XNodeArray.cs b/src/CustomProviders/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 000000000000..1a3e572861f9 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Debugging.cs b/src/CustomProviders/generated/runtime/Debugging.cs new file mode 100644 index 000000000000..5a899cce43b1 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/DictionaryExtensions.cs b/src/CustomProviders/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 000000000000..85bb55535a85 --- /dev/null +++ b/src/CustomProviders/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + if (value is System.Collections.Hashtable nested) + { + HashTableToDictionary(nested, new System.Collections.Generic.Dictionary()); + } + else + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/EventData.cs b/src/CustomProviders/generated/runtime/EventData.cs new file mode 100644 index 000000000000..2f2cb6f68b5f --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/EventDataExtensions.cs b/src/CustomProviders/generated/runtime/EventDataExtensions.cs new file mode 100644 index 000000000000..f93a59f0e887 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime +{ + using System; + + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/EventListener.cs b/src/CustomProviders/generated/runtime/EventListener.cs new file mode 100644 index 000000000000..3407497d16c7 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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.CustomProviders.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/generated/runtime/Events.cs b/src/CustomProviders/generated/runtime/Events.cs new file mode 100644 index 000000000000..de2e19d650c9 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/EventsExtensions.cs b/src/CustomProviders/generated/runtime/EventsExtensions.cs new file mode 100644 index 000000000000..4667d4ad41e0 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Extensions.cs b/src/CustomProviders/generated/runtime/Extensions.cs new file mode 100644 index 000000000000..866d69ff2e03 --- /dev/null +++ b/src/CustomProviders/generated/runtime/Extensions.cs @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + using System.Linq; + + internal static partial class Extensions + { + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => headerName == each.Key).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/src/CustomProviders/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 000000000000..e22c1a18b0f9 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/src/CustomProviders/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 000000000000..5f460bdd2281 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Helpers/Seperator.cs b/src/CustomProviders/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 000000000000..fb8fe9a82be1 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Helpers/TypeDetails.cs b/src/CustomProviders/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 000000000000..89bd735f37e1 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Helpers/XHelper.cs b/src/CustomProviders/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 000000000000..b25392dfb884 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/HttpPipeline.cs b/src/CustomProviders/generated/runtime/HttpPipeline.cs new file mode 100644 index 000000000000..cbee6b7f1e98 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/HttpPipelineMocking.ps1 b/src/CustomProviders/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 000000000000..1cec44082e54 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/IAssociativeArray.cs b/src/CustomProviders/generated/runtime/IAssociativeArray.cs new file mode 100644 index 000000000000..d3078cf446ae --- /dev/null +++ b/src/CustomProviders/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + int Count { get; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/IHeaderSerializable.cs b/src/CustomProviders/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 000000000000..70fd974e9237 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/ISendAsync.cs b/src/CustomProviders/generated/runtime/ISendAsync.cs new file mode 100644 index 000000000000..d687777b8888 --- /dev/null +++ b/src/CustomProviders/generated/runtime/ISendAsync.cs @@ -0,0 +1,289 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/InfoAttribute.cs b/src/CustomProviders/generated/runtime/InfoAttribute.cs new file mode 100644 index 000000000000..29409ef80348 --- /dev/null +++ b/src/CustomProviders/generated/runtime/InfoAttribute.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Iso/IsoDate.cs b/src/CustomProviders/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 000000000000..ba1afa05af09 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/JsonType.cs b/src/CustomProviders/generated/runtime/JsonType.cs new file mode 100644 index 000000000000..bf37cf8fa8a1 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Method.cs b/src/CustomProviders/generated/runtime/Method.cs new file mode 100644 index 000000000000..2fd5c9b50141 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Models/JsonMember.cs b/src/CustomProviders/generated/runtime/Models/JsonMember.cs new file mode 100644 index 000000000000..19999fb37fc2 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Models/JsonModel.cs b/src/CustomProviders/generated/runtime/Models/JsonModel.cs new file mode 100644 index 000000000000..4bcab9abf5ff --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Models/JsonModelCache.cs b/src/CustomProviders/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 000000000000..2a76e8d8ea54 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/Collections/JsonArray.cs b/src/CustomProviders/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 000000000000..8df845c3c187 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/Collections/XImmutableArray.cs b/src/CustomProviders/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 000000000000..f4d96ef17f26 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/Collections/XList.cs b/src/CustomProviders/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 000000000000..d328f1a3338d --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/Collections/XNodeArray.cs b/src/CustomProviders/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 000000000000..8b6358041351 --- /dev/null +++ b/src/CustomProviders/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Nodes/Collections/XSet.cs b/src/CustomProviders/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 000000000000..f7de16474756 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/JsonBoolean.cs b/src/CustomProviders/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 000000000000..23b2aa942876 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/JsonDate.cs b/src/CustomProviders/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 000000000000..792a82e4c2aa --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/JsonNode.cs b/src/CustomProviders/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 000000000000..6d142625ff1d --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/JsonNumber.cs b/src/CustomProviders/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 000000000000..8b56a4de63c7 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Nodes/JsonObject.cs b/src/CustomProviders/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 000000000000..ad496eafb7b9 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/JsonString.cs b/src/CustomProviders/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 000000000000..23d093970a5d --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/XBinary.cs b/src/CustomProviders/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 000000000000..05284150bf7c --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Nodes/XNull.cs b/src/CustomProviders/generated/runtime/Nodes/XNull.cs new file mode 100644 index 000000000000..e8989f8651f1 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Parser/Exceptions/ParseException.cs b/src/CustomProviders/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 000000000000..a65a1332f704 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Parser/JsonParser.cs b/src/CustomProviders/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 000000000000..eda2110afd0e --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Parser/JsonToken.cs b/src/CustomProviders/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 000000000000..f99c0a2e2599 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Parser/JsonTokenizer.cs b/src/CustomProviders/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 000000000000..5c054d482716 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Parser/Location.cs b/src/CustomProviders/generated/runtime/Parser/Location.cs new file mode 100644 index 000000000000..a981fd179fb4 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Parser/Readers/SourceReader.cs b/src/CustomProviders/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 000000000000..7fa47c866ae1 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Parser/TokenReader.cs b/src/CustomProviders/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 000000000000..ad853edc790d --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/PipelineMocking.cs b/src/CustomProviders/generated/runtime/PipelineMocking.cs new file mode 100644 index 000000000000..45c61601e480 --- /dev/null +++ b/src/CustomProviders/generated/runtime/PipelineMocking.cs @@ -0,0 +1,254 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result); + + internal static JsonNode SerializeContent(byte[] content) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (content.EndsWith("==")) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content) }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content) }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"))) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"))) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Response.cs b/src/CustomProviders/generated/runtime/Response.cs new file mode 100644 index 000000000000..7accd48ac15d --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Serialization/JsonSerializer.cs b/src/CustomProviders/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 000000000000..ffa7aba89ffb --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Serialization/PropertyTransformation.cs b/src/CustomProviders/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 000000000000..6a4ae7edfbfe --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/Serialization/SerializationOptions.cs b/src/CustomProviders/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 000000000000..6450b2d2d028 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/SerializationMode.cs b/src/CustomProviders/generated/runtime/SerializationMode.cs new file mode 100644 index 000000000000..2b5aef4cb7f3 --- /dev/null +++ b/src/CustomProviders/generated/runtime/SerializationMode.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeReadOnly = 1 << 1, + + IncludeAll = IncludeHeaders | IncludeReadOnly + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/TypeConverterExtensions.cs b/src/CustomProviders/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 000000000000..04664dd70911 --- /dev/null +++ b/src/CustomProviders/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + } +} diff --git a/src/CustomProviders/generated/runtime/UndeclaredResponseException.cs b/src/CustomProviders/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 000000000000..1988a0b51524 --- /dev/null +++ b/src/CustomProviders/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.Json.JsonObject; + + // see if there is an error block in the body + json = json.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // we'll create one below. + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/generated/runtime/Writers/JsonWriter.cs b/src/CustomProviders/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 000000000000..61f32af7f18c --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/generated/runtime/delegates.cs b/src/CustomProviders/generated/runtime/delegates.cs new file mode 100644 index 000000000000..027cc96e4737 --- /dev/null +++ b/src/CustomProviders/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.CustomProviders.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/CustomProviders/help/Az.CustomProviders.md b/src/CustomProviders/help/Az.CustomProviders.md new file mode 100644 index 000000000000..a977a2aa2b15 --- /dev/null +++ b/src/CustomProviders/help/Az.CustomProviders.md @@ -0,0 +1,35 @@ +--- +Module Name: Az.CustomProviders +Module Guid: b98dded0-6e9a-4371-b2c6-d74464fb724b +Download Help Link: https://docs.microsoft.com/en-us/powershell/module/az.customproviders +Help Version: 1.0.0.0 +Locale: en-US +--- + +# Az.CustomProviders Module +## Description +Microsoft Azure PowerShell: Custom Providers cmdlets + +## Az.CustomProviders Cmdlets +### [Get-AzCustomProvider](Get-AzCustomProvider.md) +Gets the custom resource provider manifest. + +### [Get-AzCustomProviderAssociation](Get-AzCustomProviderAssociation.md) +Get an association. + +### [New-AzCustomProvider](New-AzCustomProvider.md) +Creates or updates the custom resource provider. + +### [New-AzCustomProviderAssociation](New-AzCustomProviderAssociation.md) +Create or update an association. + +### [Remove-AzCustomProvider](Remove-AzCustomProvider.md) +Deletes the custom resource provider. + +### [Remove-AzCustomProviderAssociation](Remove-AzCustomProviderAssociation.md) +Delete an association. + +### [Update-AzCustomProvider](Update-AzCustomProvider.md) +Updates an existing custom resource provider. +The only value that can be updated via PATCH currently is the tags. + diff --git a/src/CustomProviders/help/Get-AzCustomProvider.md b/src/CustomProviders/help/Get-AzCustomProvider.md new file mode 100644 index 000000000000..7c4527dedfa7 --- /dev/null +++ b/src/CustomProviders/help/Get-AzCustomProvider.md @@ -0,0 +1,182 @@ +--- +external help file: +Module Name: Az.CustomProviders +online version: https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azcustomprovider +schema: 2.0.0 +--- + +# Get-AzCustomProvider + +## SYNOPSIS +Gets the custom resource provider manifest. + +## SYNTAX + +### List1 (Default) +``` +Get-AzCustomProvider [-SubscriptionId ] [-DefaultProfile ] [] +``` + +### Get +``` +Get-AzCustomProvider -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [] +``` + +### GetViaIdentity +``` +Get-AzCustomProvider -InputObject [-DefaultProfile ] [] +``` + +### List +``` +Get-AzCustomProvider -ResourceGroupName [-SubscriptionId ] [-DefaultProfile ] + [] +``` + +## DESCRIPTION +Gets the custom resource provider manifest. + +## EXAMPLES + +### Example 1: List all Custom Providers in a subscription +```powershell +PS C:\> Get-AzCustomProvider + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +East US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders +``` + +Lists all the custom providers in a subscription + +### Example 2: Get a single custom provider +```powershell +PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : + +``` + +Gets details for a single custom provider. +Use Format-List to show object details on the screen. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the resource provider. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: ResourceProviderName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Azure subscription ID. +This is a GUID-formatted string (e.g. +00000000-0000-0000-0000-000000000000) + +```yaml +Type: System.String[] +Parameter Sets: Get, List, List1 +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[AssociationName ]`: The name of the association. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. + - `[ResourceProviderName ]`: The name of the resource provider. + - `[Scope ]`: The scope of the association. + - `[SubscriptionId ]`: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + +## RELATED LINKS + diff --git a/src/CustomProviders/help/Get-AzCustomProviderAssociation.md b/src/CustomProviders/help/Get-AzCustomProviderAssociation.md new file mode 100644 index 000000000000..b36ed8acd8cc --- /dev/null +++ b/src/CustomProviders/help/Get-AzCustomProviderAssociation.md @@ -0,0 +1,151 @@ +--- +external help file: +Module Name: Az.CustomProviders +online version: https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azcustomproviderassociation +schema: 2.0.0 +--- + +# Get-AzCustomProviderAssociation + +## SYNOPSIS +Get an association. + +## SYNTAX + +### List (Default) +``` +Get-AzCustomProviderAssociation -Scope [-DefaultProfile ] [] +``` + +### Get +``` +Get-AzCustomProviderAssociation -Name -Scope [-DefaultProfile ] + [] +``` + +### GetViaIdentity +``` +Get-AzCustomProviderAssociation -InputObject [-DefaultProfile ] + [] +``` + +## DESCRIPTION +Get an association. + +## EXAMPLES + +### Example 1: List custom provider associations +```powershell +PS C:\> Get-AzCustomProviderAssociation + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +``` + +List all custom provider associations for a given scope. + +### Example 2: Get an association +```powershell +PS C:\> Get-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +``` + +Get details for a single CustomProvider association + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the association. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: AssociationName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope +The scope of the association. + +```yaml +Type: System.String +Parameter Sets: Get, List +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 + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[AssociationName ]`: The name of the association. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. + - `[ResourceProviderName ]`: The name of the resource provider. + - `[Scope ]`: The scope of the association. + - `[SubscriptionId ]`: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + +## RELATED LINKS + diff --git a/src/CustomProviders/help/New-AzCustomProvider.md b/src/CustomProviders/help/New-AzCustomProvider.md new file mode 100644 index 000000000000..c73341234fc9 --- /dev/null +++ b/src/CustomProviders/help/New-AzCustomProvider.md @@ -0,0 +1,286 @@ +--- +external help file: +Module Name: Az.CustomProviders +online version: https://docs.microsoft.com/en-us/powershell/module/az.customproviders/new-azcustomprovider +schema: 2.0.0 +--- + +# New-AzCustomProvider + +## SYNOPSIS +Creates or updates the custom resource provider. + +## SYNTAX + +``` +New-AzCustomProvider -Name -ResourceGroupName -Location [-SubscriptionId ] + [-Action ] [-ResourceType ] + [-Tag ] [-Validation ] [-DefaultProfile ] [-AsJob] [-NoWait] + [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Creates or updates the custom resource provider. + +## EXAMPLES + +### Example 1: Create a custom provider +```powershell +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"} + + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +``` + +Create a custom resource provider + +### Example 2: Create a custom provider with associations +```powershell +PS C:\> New-AzCustomProvider -ResourceGroupName myRG -Name Namespace2.Type -Location "West US 2" -ResourceType @{Name="CustomRoute1"; Endpoint="https://www.contoso.com/"}, @{Name="Associations"; Endpoint="https://contoso.com/myService", RoutingType="Proxy,Cache,Extension"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace2.Type Microsoft.CustomProviders/resourceproviders +``` + +Create a custom provider, with a route for Custom provider associations. + +## PARAMETERS + +### -Action +A list of actions that the custom resource provider implements. +To construct, see NOTES section for ACTION properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpActionRouteDefinition[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Location +Resource location + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +The name of the resource provider. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: ResourceProviderName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceType +A list of resource types that the custom resource provider implements. +To construct, see NOTES section for RESOURCETYPE properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpResourceTypeRouteDefinition[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Azure subscription ID. +This is a GUID-formatted string (e.g. +00000000-0000-0000-0000-000000000000) + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +Resource tags + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Validation +A list of validations to run on the custom resource provider's requests. +To construct, see NOTES section for VALIDATION properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpValidations[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +ACTION : A list of actions that the custom resource provider implements. + - `Endpoint `: The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + - `Name `: The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + - `[RoutingType ]`: The routing types that are supported for action requests. + +RESOURCETYPE : A list of resource types that the custom resource provider implements. + - `Endpoint `: The route definition endpoint URI that the custom resource provider will proxy requests to. This can be in the form of a flat URI (e.g. 'https://testendpoint/') or can specify to route via a path (e.g. 'https://testendpoint/{requestPath}') + - `Name `: The name of the route definition. This becomes the name for the ARM extension (e.g. '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomProviders/resourceProviders/{resourceProviderName}/{name}') + - `[RoutingType ]`: The routing types that are supported for resource requests. + +VALIDATION : A list of validations to run on the custom resource provider's requests. + - `Specification `: A link to the validation specification. The specification must be hosted on raw.githubusercontent.com. + - `[ValidationType ]`: The type of validation to run against a matching request. + +## RELATED LINKS + diff --git a/src/CustomProviders/help/New-AzCustomProviderAssociation.md b/src/CustomProviders/help/New-AzCustomProviderAssociation.md new file mode 100644 index 000000000000..df1b60301974 --- /dev/null +++ b/src/CustomProviders/help/New-AzCustomProviderAssociation.md @@ -0,0 +1,176 @@ +--- +external help file: +Module Name: Az.CustomProviders +online version: https://docs.microsoft.com/en-us/powershell/module/az.customproviders/new-azcustomproviderassociation +schema: 2.0.0 +--- + +# New-AzCustomProviderAssociation + +## SYNOPSIS +Create or update an association. + +## SYNTAX + +``` +New-AzCustomProviderAssociation -Name -Scope [-TargetResourceId ] + [-DefaultProfile ] [-AsJob] [-NoWait] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Create or update an association. + +## EXAMPLES + +### Example 1: Create a custom provider association +```powershell +PS C:\> $provider = Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +PS C:\> New-AzCustomProviderAssociation -Scope $resourceId -Name MyAssoc -TargetResourceId $provider.Id + +Location Name Type +-------- ---- ---- +East US 2 MyAssoc Microsoft.CustomProviders/associations +``` + +Create a custom provider association, the associated target provioder must be properly configured with a route for "associations" + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +The name of the association. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: AssociationName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope +The scope of the association. +The scope can be any valid REST resource instance. +For example, use '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/{vm-name}' for a virtual machine resource. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TargetResourceId +The REST resource instance of the target resource for this association. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IAssociation + +## NOTES + +ALIASES + +## RELATED LINKS + diff --git a/src/CustomProviders/help/Remove-AzCustomProvider.md b/src/CustomProviders/help/Remove-AzCustomProvider.md new file mode 100644 index 000000000000..2a0e5977fa49 --- /dev/null +++ b/src/CustomProviders/help/Remove-AzCustomProvider.md @@ -0,0 +1,233 @@ +--- +external help file: +Module Name: Az.CustomProviders +online version: https://docs.microsoft.com/en-us/powershell/module/az.customproviders/remove-azcustomprovider +schema: 2.0.0 +--- + +# Remove-AzCustomProvider + +## SYNOPSIS +Deletes the custom resource provider. + +## SYNTAX + +### Delete (Default) +``` +Remove-AzCustomProvider -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [-AsJob] [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +### DeleteViaIdentity +``` +Remove-AzCustomProvider -InputObject [-DefaultProfile ] [-AsJob] + [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Deletes the custom resource provider. + +## EXAMPLES + +### Example 1: Remove a custom provider. +```powershell +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type +``` + +Remove a custom provider + +### Example 2: Remove a custom provider with PassThru +```powershell +PS C:\> PS C:\> Remove-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -PassThru + +True +``` + +Remove a custom provider, using the PassThru feature to indicate success or failure. + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the resource provider. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: ResourceProviderName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Azure subscription ID. +This is a GUID-formatted string (e.g. +00000000-0000-0000-0000-000000000000) + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[AssociationName ]`: The name of the association. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. + - `[ResourceProviderName ]`: The name of the resource provider. + - `[Scope ]`: The scope of the association. + - `[SubscriptionId ]`: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + +## RELATED LINKS + diff --git a/src/CustomProviders/help/Remove-AzCustomProviderAssociation.md b/src/CustomProviders/help/Remove-AzCustomProviderAssociation.md new file mode 100644 index 000000000000..77a1ee4da396 --- /dev/null +++ b/src/CustomProviders/help/Remove-AzCustomProviderAssociation.md @@ -0,0 +1,216 @@ +--- +external help file: +Module Name: Az.CustomProviders +online version: https://docs.microsoft.com/en-us/powershell/module/az.customproviders/remove-azcustomproviderassociation +schema: 2.0.0 +--- + +# Remove-AzCustomProviderAssociation + +## SYNOPSIS +Delete an association. + +## SYNTAX + +### Delete (Default) +``` +Remove-AzCustomProviderAssociation -Name -Scope [-DefaultProfile ] [-AsJob] + [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +### DeleteViaIdentity +``` +Remove-AzCustomProviderAssociation -InputObject [-DefaultProfile ] + [-AsJob] [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Delete an association. + +## EXAMPLES + +### Example 1: Remove a custom provider association. +```powershell +PS C:\> PS C:\> Remove-AzCustomProviderAssociation -Scope $id -Name Namespace.Type +``` + +Remove a custom provider association. + +### Example 2: Remove a custom provider association with Piping +```powershell +PS C:\> PS C:\> Get-AzCustomProviderAssociation | Remove-AzCustomProviderAssociation -PassThru + +True +``` + +Remove a custom provider association, using piping and the PassThru feature to indicate success or failure. + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the association. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: AssociationName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope +The scope of the association. + +```yaml +Type: System.String +Parameter Sets: Delete +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.CustomProviders.Models.ICustomProvidersIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[AssociationName ]`: The name of the association. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. + - `[ResourceProviderName ]`: The name of the resource provider. + - `[Scope ]`: The scope of the association. + - `[SubscriptionId ]`: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + +## RELATED LINKS + diff --git a/src/CustomProviders/help/Update-AzCustomProvider.md b/src/CustomProviders/help/Update-AzCustomProvider.md new file mode 100644 index 000000000000..24a6dcf55977 --- /dev/null +++ b/src/CustomProviders/help/Update-AzCustomProvider.md @@ -0,0 +1,217 @@ +--- +external help file: +Module Name: Az.CustomProviders +online version: https://docs.microsoft.com/en-us/powershell/module/az.customproviders/update-azcustomprovider +schema: 2.0.0 +--- + +# Update-AzCustomProvider + +## SYNOPSIS +Updates an existing custom resource provider. +The only value that can be updated via PATCH currently is the tags. + +## SYNTAX + +### UpdateExpanded (Default) +``` +Update-AzCustomProvider -Name -ResourceGroupName [-SubscriptionId ] + [-Tag ] [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +### UpdateViaIdentityExpanded +``` +Update-AzCustomProvider -InputObject [-Tag ] + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Updates an existing custom resource provider. +The only value that can be updated via PATCH currently is the tags. + +## EXAMPLES + +### Example 1: Add Tags to a custom Provider +```powershell +PS C:\> Update-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type -Tag @{MyTag="MyValue"} | Format-List + +Action : +Id : /subscriptions/xxxxx-yyyyy-xxxx-yyyy/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Namespace.Type +Location : West US 2 +Name : Namespace.Type +ProvisioningState : Succeeded +ResourceType : {CustomRoute1, associations} +Tag : Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ResourceTags +Type : Microsoft.CustomProviders/resourceproviders +Validation : +``` + +Update the tags of a custom provider. + +### Example 2: Update custom provider with piping +```powershell +PS C:\> PS C:\> Get-AzCustomProvider -ResourceGroupName myRg -Name Namespace.Type | Update-AzCustomProvider -Tag @{MyTag="MyValue"} + +Location Name Type +-------- ---- ---- +West US 2 Namespace.Type Microsoft.CustomProviders/resourceproviders +``` + +Update a custom provider using piping. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity +Parameter Sets: UpdateViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +The name of the resource provider. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: ResourceProviderName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Azure subscription ID. +This is a GUID-formatted string (e.g. +00000000-0000-0000-0000-000000000000) + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +Resource tags + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.ICustomProvidersIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.ICustomRpManifest + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[AssociationName ]`: The name of the association. + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. + - `[ResourceProviderName ]`: The name of the resource provider. + - `[Scope ]`: The scope of the association. + - `[SubscriptionId ]`: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + +## RELATED LINKS + diff --git a/src/CustomProviders/how-to.md b/src/CustomProviders/how-to.md new file mode 100644 index 000000000000..ea7fae90e708 --- /dev/null +++ b/src/CustomProviders/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.CustomProviders`. + +## Building `Az.CustomProviders` +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.CustomProviders` +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.CustomProviders` +To pack `Az.CustomProviders` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://docs.microsoft.com/en-us/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.CustomProviders`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.CustomProviders.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.CustomProviders.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.CustomProviders`. + - `-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.CustomProviders` 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/CustomProviders/internal/Az.CustomProviders.internal.psm1 b/src/CustomProviders/internal/Az.CustomProviders.internal.psm1 new file mode 100644 index 000000000000..47ad8be59aa5 --- /dev/null +++ b/src/CustomProviders/internal/Az.CustomProviders.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.CustomProviders.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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/CustomProviders/internal/Get-AzOperation.ps1 b/src/CustomProviders/internal/Get-AzOperation.ps1 new file mode 100644 index 000000000000..50bd8437bf0e --- /dev/null +++ b/src/CustomProviders/internal/Get-AzOperation.ps1 @@ -0,0 +1,121 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +The list of operations provided by Microsoft CustomProviders. +.Description +The list of operations provided by Microsoft CustomProviders. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azoperation +#> +function Get-AzOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.private\Get-AzOperation_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/CustomProviders/internal/ProxyCmdletDefinitions.ps1 b/src/CustomProviders/internal/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..50bd8437bf0e --- /dev/null +++ b/src/CustomProviders/internal/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,121 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +The list of operations provided by Microsoft CustomProviders. +.Description +The list of operations provided by Microsoft CustomProviders. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.customproviders/get-azoperation +#> +function Get-AzOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Models.Api20180901Preview.IResourceProviderOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.CustomProviders.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.CustomProviders.private\Get-AzOperation_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/CustomProviders/internal/readme.md b/src/CustomProviders/internal/readme.md new file mode 100644 index 000000000000..dc3843a14861 --- /dev/null +++ b/src/CustomProviders/internal/readme.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.CustomProviders.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.CustomProviders`. Instead, this sub-module is imported by the `..\custom\Az.CustomProviders.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.CustomProviders.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.CustomProviders`. \ No newline at end of file diff --git a/src/CustomProviders/pack-module.ps1 b/src/CustomProviders/pack-module.ps1 new file mode 100644 index 000000000000..c22fad33d87b --- /dev/null +++ b/src/CustomProviders/pack-module.ps1 @@ -0,0 +1,16 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/CustomProviders/readme.md b/src/CustomProviders/readme.md new file mode 100644 index 000000000000..7bb2c69f9c4d --- /dev/null +++ b/src/CustomProviders/readme.md @@ -0,0 +1,116 @@ + +# Az.CustomProviders +This directory contains the PowerShell module for the CustomProviders service. + +--- +## Status +[![Az.CustomProviders](https://img.shields.io/powershellgallery/v/Az.CustomProviders.svg?style=flat-square&label=Az.CustomProviders "Az.CustomProviders")](https://www.powershellgallery.com/packages/Az.CustomProviders/) + +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 1.8.1 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.CustomProviders`, see [how-to.md](how-to.md). + + +## Run Generation +In this directory, run AutoRest: +> `autorest` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +``` yaml +require: + - $(this-folder)/../readme.azure.noprofile.md +input-file: + - $(repo)/specification/customproviders/resource-manager/Microsoft.CustomProviders/preview/2018-09-01-preview/customproviders.json + +metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + description: 'Microsoft Azure PowerShell: Custom Providers cmdlets' + copyright: Microsoft Corporation. All rights reserved. + tags: Azure ResourceManager ARM PSModule CustomProviders + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell + releaseNotes: Initial release of CustomProviders cmdlets. + +module-version: 0.1.0 +title: CustomProviders +subject-prefix: '' + +directive: + - where: + subject: CustomResourceProvider + set: + subject: CustomProvider + + - where: + subject: Association + set: + subject: CustomProviderAssociation + + - where: + verb: New + subject: ^CustomProvider.*$ + variant: ^CreateViaIdentity$|^CreateViaIdentityExpanded$|^Create$ + remove: true + + - where: + verb: Set + subject: CustomProviderAssociation + variant: ^Update$|^UpdateViaIdentity$ + remove: true + + - where: + verb: Set + subject: ^CustomProvider$ + remove: true + + - where: + verb: Update + subject: CustomProvider + variant: ^Update$|^UpdateViaIdentity$ + remove: true + + - where: + verb: Set + subject: CustomProviderAssociation + remove: true + +# Parameter renames + - where: + subject: ^CustomProvider$ + parameter-name: ResourceProviderName + set: + parameter-name: Name + alias: ResourceProviderName + +# Make ResourceId validation case insensitive + - from: source-file-csharp + where: $ + transform: $ = $.replace(/var _match = new global\:\:System\.Text\.RegularExpressions\.Regex\(\"([^\"]+)\"\).Match\(viaIdentity\);/g, 'var _match = new global\:\:System.Text.RegularExpressions.Regex\(\"$1\", global\:\:System\.Text\.RegularExpressions\.RegexOptions\.IgnoreCase\).Match\(viaIdentity\);'); + +# Fix issue with delete LRO operations + - from: source-file-csharp + where: $ + transform: $ = $.replace(/var _finalUri = _response.GetFirstHeader\(\@\"Location\"\);/g, 'var _finalUri = \"\";'); + +``` diff --git a/src/CustomProviders/run-module.ps1 b/src/CustomProviders/run-module.ps1 new file mode 100644 index 000000000000..c2aae6c06335 --- /dev/null +++ b/src/CustomProviders/run-module.ps1 @@ -0,0 +1,59 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.CustomProviders.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/CustomProviders/test-module.ps1 b/src/CustomProviders/test-module.ps1 new file mode 100644 index 000000000000..f6ad0ab44e36 --- /dev/null +++ b/src/CustomProviders/test-module.ps1 @@ -0,0 +1,68 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Live, [switch]$Record, [switch]$Playback) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts:$false -Pester -Resources:$requireResourceModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) { + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.CustomProviders.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +if($Live) { + $TestMode = 'live' +} +if($Record) { + $TestMode = 'record' +} +try { + if ($TestMode -ne 'playback') { + setupEnv + } + $testFolder = Join-Path $PSScriptRoot 'test' + Invoke-Pester -Script @{ Path = $testFolder } -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") +} +Finally +{ + if ($TestMode -ne 'playback') { + cleanupEnv + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/CustomProviders/test/Az.CustomProviderCrud.Recording.json b/src/CustomProviders/test/Az.CustomProviderCrud.Recording.json new file mode 100644 index 000000000000..c6b1789bae16 --- /dev/null +++ b/src/CustomProviders/test/Az.CustomProviderCrud.Recording.json @@ -0,0 +1,349 @@ +{ + "Az CustomProvider Crud+[NoContext]+Lists all custom providers in a subscription+$GET+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.CustomProviders/resourceProviders?api-version=2018-09-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/providers/Microsoft.CustomProviders/resourceProviders?api-version=2018-09-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "2" ], + "x-ms-client-request-id": [ "c85ef648-8fa3-4727-a6ce-4a02f2743636" ], + "CommandName": [ "Get-AzCustomProvider" ], + "FullCommandName": [ "Get-AzCustomProvider_List1" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-request-id": [ "aa74c04a-7047-43a7-95d4-67ddc5146abb" ], + "x-ms-correlation-request-id": [ "06a60f0c-d9b7-40b4-a77f-ae3f3fa9fa73" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043220Z:aa74c04a-7047-43a7-95d4-67ddc5146abb" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11999" ], + "Date": [ "Fri, 26 Jun 2020 04:32:19 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "543" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[{\"properties\":{\"resourceTypes\":[{\"name\":\"CustomRoute1\",\"routingType\":\"Proxy\",\"endpoint\":\"https://www.microsoft.com/\"},{\"name\":\"associations\",\"routingType\":\"Proxy, Extension, Cache\",\"endpoint\":\"https://docs.microsoft.com\"}],\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/mc-cp01/providers/Microsoft.CustomProviders/resourceproviders/Microsoft.ComputeMine\",\"name\":\"Microsoft.ComputeMine\",\"type\":\"Microsoft.CustomProviders/resourceproviders\",\"location\":\"West US 2\",\"tags\":{}}]}" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$PUT+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview", + "Content": "{\r\n \"location\": \"West US 2\",\r\n \"properties\": {\r\n \"resourceTypes\": [\r\n {\r\n \"name\": \"CustomRoute1\",\r\n \"endpoint\": \"https://www.microsoft.com/\"\r\n },\r\n {\r\n \"name\": \"associations\",\r\n \"endpoint\": \"https://docs.microsoft.com\",\r\n \"routingType\": \"Proxy,Cache,Extension\"\r\n }\r\n ]\r\n }\r\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "339" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Retry-After": [ "15" ], + "Azure-AsyncOperation": [ "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West%20US%202/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview" ], + "x-ms-request-id": [ "87f8aef7-6205-47cd-84c7-89890935ec1f" ], + "x-ms-correlation-request-id": [ "a5488825-57c8-4678-abcd-0e5b776fd850" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043222Z:87f8aef7-6205-47cd-84c7-89890935ec1f" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1199" ], + "Date": [ "Fri, 26 Jun 2020 04:32:22 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "524" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"properties\":{\"resourceTypes\":[{\"name\":\"CustomRoute1\",\"routingType\":\"Proxy\",\"endpoint\":\"https://www.microsoft.com/\"},{\"name\":\"associations\",\"routingType\":\"Proxy, Extension, Cache\",\"endpoint\":\"https://docs.microsoft.com\"}],\"provisioningState\":\"Accepted\"},\"id\":\"/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceproviders/MSTest.MyTesth2niy\",\"name\":\"MSTest.MyTesth2niy\",\"type\":\"Microsoft.CustomProviders/resourceproviders\",\"location\":\"West US 2\",\"tags\":{}}" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$GET+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West US 2/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West%20US%202/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "3", "4" ], + "x-ms-client-request-id": [ "25c68b2f-3d49-48b1-86dd-c9b841b6be7c", "25c68b2f-3d49-48b1-86dd-c9b841b6be7c" ], + "CommandName": [ "New-AzCustomProvider", "New-AzCustomProvider" ], + "FullCommandName": [ "New-AzCustomProvider_CreateExpanded", "New-AzCustomProvider_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West%20US%202/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview" ], + "x-ms-request-id": [ "a4e887d0-6df7-4791-90ce-84bad09af47c" ], + "x-ms-correlation-request-id": [ "a5488825-57c8-4678-abcd-0e5b776fd850" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043238Z:a4e887d0-6df7-4791-90ce-84bad09af47c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11998" ], + "Date": [ "Fri, 26 Jun 2020 04:32:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "22" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"status\":\"Succeeded\"}" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$GET+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "3", "4", "5" ], + "x-ms-client-request-id": [ "25c68b2f-3d49-48b1-86dd-c9b841b6be7c", "25c68b2f-3d49-48b1-86dd-c9b841b6be7c", "25c68b2f-3d49-48b1-86dd-c9b841b6be7c" ], + "CommandName": [ "New-AzCustomProvider", "New-AzCustomProvider", "New-AzCustomProvider" ], + "FullCommandName": [ "New-AzCustomProvider_CreateExpanded", "New-AzCustomProvider_CreateExpanded", "New-AzCustomProvider_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-request-id": [ "a9cf1545-ab2f-4356-acc7-241820e316b3" ], + "x-ms-correlation-request-id": [ "94ee996b-4814-4f6e-a312-e713410af331" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043238Z:a9cf1545-ab2f-4356-acc7-241820e316b3" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11997" ], + "Date": [ "Fri, 26 Jun 2020 04:32:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "525" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"properties\":{\"resourceTypes\":[{\"name\":\"CustomRoute1\",\"routingType\":\"Proxy\",\"endpoint\":\"https://www.microsoft.com/\"},{\"name\":\"associations\",\"routingType\":\"Proxy, Extension, Cache\",\"endpoint\":\"https://docs.microsoft.com\"}],\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceproviders/MSTest.MyTesth2niy\",\"name\":\"MSTest.MyTesth2niy\",\"type\":\"Microsoft.CustomProviders/resourceproviders\",\"location\":\"West US 2\",\"tags\":{}}" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$PATCH+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview+4": { + "Request": { + "Method": "PATCH", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview", + "Content": "{\r\n \"tags\": {\r\n \"MyTag1\": \"MyValue1\",\r\n \"MyTag2\": \"MyValue2\"\r\n }\r\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "75" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-request-id": [ "1b87c999-8e50-442b-80f2-1e2bf9d72fe6" ], + "x-ms-correlation-request-id": [ "c2448e48-7ac6-4416-90d6-886dee079070" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043238Z:1b87c999-8e50-442b-80f2-1e2bf9d72fe6" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1198" ], + "Date": [ "Fri, 26 Jun 2020 04:32:38 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "564" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"properties\":{\"resourceTypes\":[{\"name\":\"CustomRoute1\",\"routingType\":\"Proxy\",\"endpoint\":\"https://www.microsoft.com/\"},{\"name\":\"associations\",\"routingType\":\"Proxy, Extension, Cache\",\"endpoint\":\"https://docs.microsoft.com\"}],\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceproviders/MSTest.MyTesth2niy\",\"name\":\"MSTest.MyTesth2niy\",\"type\":\"Microsoft.CustomProviders/resourceproviders\",\"location\":\"West US 2\",\"tags\":{\"MyTag1\":\"MyValue1\",\"MyTag2\":\"MyValue2\"}}" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$GET+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "7" ], + "x-ms-client-request-id": [ "b1bcee40-a86a-4de2-82e9-83b3bc692c93" ], + "CommandName": [ "Get-AzCustomProvider" ], + "FullCommandName": [ "Get-AzCustomProvider_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-request-id": [ "24ee036e-d59d-4931-a27a-d56db37e1cd7" ], + "x-ms-correlation-request-id": [ "bcbe20d8-7ef0-4b20-b535-eef6a444d95a" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043239Z:24ee036e-d59d-4931-a27a-d56db37e1cd7" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11996" ], + "Date": [ "Fri, 26 Jun 2020 04:32:38 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "564" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"properties\":{\"resourceTypes\":[{\"name\":\"CustomRoute1\",\"routingType\":\"Proxy\",\"endpoint\":\"https://www.microsoft.com/\"},{\"name\":\"associations\",\"routingType\":\"Proxy, Extension, Cache\",\"endpoint\":\"https://docs.microsoft.com\"}],\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceproviders/MSTest.MyTesth2niy\",\"name\":\"MSTest.MyTesth2niy\",\"type\":\"Microsoft.CustomProviders/resourceproviders\",\"location\":\"West US 2\",\"tags\":{\"MyTag1\":\"MyValue1\",\"MyTag2\":\"MyValue2\"}}" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$DELETE+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview+6": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8" ], + "x-ms-client-request-id": [ "e5c3bde1-86ce-4584-ad44-9b26227c8350" ], + "CommandName": [ "Remove-AzCustomProvider" ], + "FullCommandName": [ "Remove-AzCustomProvider_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West%20US%202/operationresults/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview" ], + "Retry-After": [ "15" ], + "Azure-AsyncOperation": [ "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West%20US%202/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview" ], + "x-ms-request-id": [ "42682820-ad38-4d14-b079-a2c56f97a5d2" ], + "x-ms-correlation-request-id": [ "9b1613d5-7b8e-4fbf-bb36-87820d976c68" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043240Z:42682820-ad38-4d14-b079-a2c56f97a5d2" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14999" ], + "Date": [ "Fri, 26 Jun 2020 04:32:40 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "4" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "bnVsbA==" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$GET+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West US 2/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview+7": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West%20US%202/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8", "9" ], + "x-ms-client-request-id": [ "e5c3bde1-86ce-4584-ad44-9b26227c8350", "e5c3bde1-86ce-4584-ad44-9b26227c8350" ], + "CommandName": [ "Remove-AzCustomProvider", "Remove-AzCustomProvider" ], + "FullCommandName": [ "Remove-AzCustomProvider_DeleteViaIdentity", "Remove-AzCustomProvider_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourcegroups/rgdsw53/providers/Microsoft.CustomProviders/locations/West%20US%202/operationstatuses/eyJqb2JJZCI6Ik1SUENSVUQ6MkRSR0RTVzUzOjJETVNURVNUOjJFTVlURVNUSDJOSVkiLCJqb2JMb2NhdGlvbiI6IldFU1RVUzIifQ?api-version=2018-09-01-preview" ], + "x-ms-request-id": [ "75aca7c2-b3a7-4b2e-a2d8-13b139d72759" ], + "x-ms-correlation-request-id": [ "9b1613d5-7b8e-4fbf-bb36-87820d976c68" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043255Z:75aca7c2-b3a7-4b2e-a2d8-13b139d72759" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11995" ], + "Date": [ "Fri, 26 Jun 2020 04:32:54 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "22" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"status\":\"Succeeded\"}" + } + }, + "Az CustomProvider Crud+[NoContext]+Can Create, Update, and Remove a custom provider+$GET+https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview+8": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/c9cbd920-c00c-427c-852b-8aaf38badaeb/resourceGroups/rgdsw53/providers/Microsoft.CustomProviders/resourceProviders/MSTest.MyTesth2niy?api-version=2018-09-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "10" ], + "x-ms-client-request-id": [ "1e33f392-04fa-4bc2-b40c-3502334465af" ], + "CommandName": [ "Get-AzCustomProvider" ], + "FullCommandName": [ "Get-AzCustomProvider_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 404, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-request-id": [ "bdf4909e-3dc0-4996-8fc6-55f4ba14d843" ], + "x-ms-correlation-request-id": [ "ae839df9-f370-4ba8-9b37-72889499e8eb" ], + "x-ms-routing-request-id": [ "WESTUS2:20200626T043255Z:bdf4909e-3dc0-4996-8fc6-55f4ba14d843" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11994" ], + "Date": [ "Fri, 26 Jun 2020 04:32:54 GMT" ] + }, + "ContentHeaders": { + "Expires": [ "-1" ], + "Content-Length": [ "0" ] + }, + "Content": null + } + } +} \ No newline at end of file diff --git a/src/CustomProviders/test/AzCustomProviderCrud.Tests.ps1 b/src/CustomProviders/test/AzCustomProviderCrud.Tests.ps1 new file mode 100644 index 000000000000..207a1a0b1d5c --- /dev/null +++ b/src/CustomProviders/test/AzCustomProviderCrud.Tests.ps1 @@ -0,0 +1,33 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Az.CustomProviderCrud.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 'Az CustomProvider Crud' { + It 'Lists all custom providers in a subscription' { + $provider = Get-AzCustomProvider + $provider.Count | Should -BeGreaterOrEqual 1 + } + It 'Can Create, Update, and Remove a custom provider'{ + $resourceType = @(@{Name="CustomRoute1"; Endpoint="https://www.microsoft.com/"}, @{Name="associations"; Endpoint="https://docs.microsoft.com"; RoutingType="Proxy,Cache,Extension"}) + $provider = New-AzCustomProvider -ResourceGroupName $env.ResourceGroup -Name $env.CustomProvider -Location "West US 2" -ResourceType $resourceType + $provider | Should -Not -BeNullOrEmpty + $provider.ResourceType | Should -Not -BeNullOrEmpty + $provider.ResourceType.Count | Should -Be 2 + Update-AzCustomProvider -InputObject $provider -Tag @{MyTag1="MyValue1"; MyTag2="MyValue2"} | Out-Null + $provider2 = Get-AzCustomProvider -ResourceGroupName $env.ResourceGroup -Name $env.CustomProvider + $provider2 | Should -Not -BeNullOrEmpty + $provider2.Tag | Should -Not -BeNullOrEmpty + $provider2.Tag.Count | Should -Be 2 + Remove-AzCustomProvider -InputObject $provider2 | Out-Null + {$provider2 = Get-AzCustomProvider -ResourceGroupName $env.ResourceGroup -Name $env.CustomProvider } | Should -Throw | Out-Null + } +} diff --git a/src/CustomProviders/test/Get-AzCustomProvider.Tests.ps1 b/src/CustomProviders/test/Get-AzCustomProvider.Tests.ps1 new file mode 100644 index 000000000000..4b652cd99721 --- /dev/null +++ b/src/CustomProviders/test/Get-AzCustomProvider.Tests.ps1 @@ -0,0 +1,30 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzCustomProvider.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-AzCustomProvider' { + It 'List1' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'Get' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'List' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'GetViaIdentity' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/Get-AzCustomProviderAssociation.Tests.ps1 b/src/CustomProviders/test/Get-AzCustomProviderAssociation.Tests.ps1 new file mode 100644 index 000000000000..864ce108428d --- /dev/null +++ b/src/CustomProviders/test/Get-AzCustomProviderAssociation.Tests.ps1 @@ -0,0 +1,26 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzCustomProviderAssociation.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-AzCustomProviderAssociation' { + It 'List' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'Get' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'GetViaIdentity' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/New-AzCustomProvider.Tests.ps1 b/src/CustomProviders/test/New-AzCustomProvider.Tests.ps1 new file mode 100644 index 000000000000..70b06077379e --- /dev/null +++ b/src/CustomProviders/test/New-AzCustomProvider.Tests.ps1 @@ -0,0 +1,18 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzCustomProvider.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzCustomProvider' { + It 'CreateExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/New-AzCustomProviderAssociation.Tests.ps1 b/src/CustomProviders/test/New-AzCustomProviderAssociation.Tests.ps1 new file mode 100644 index 000000000000..30ff4eaaa71a --- /dev/null +++ b/src/CustomProviders/test/New-AzCustomProviderAssociation.Tests.ps1 @@ -0,0 +1,18 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzCustomProviderAssociation.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzCustomProviderAssociation' { + It 'CreateExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/Remove-AzCustomProvider.Tests.ps1 b/src/CustomProviders/test/Remove-AzCustomProvider.Tests.ps1 new file mode 100644 index 000000000000..b676f944ccb7 --- /dev/null +++ b/src/CustomProviders/test/Remove-AzCustomProvider.Tests.ps1 @@ -0,0 +1,22 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzCustomProvider.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzCustomProvider' { + It 'Delete' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'DeleteViaIdentity' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/Remove-AzCustomProviderAssociation.Tests.ps1 b/src/CustomProviders/test/Remove-AzCustomProviderAssociation.Tests.ps1 new file mode 100644 index 000000000000..9d6049dce12d --- /dev/null +++ b/src/CustomProviders/test/Remove-AzCustomProviderAssociation.Tests.ps1 @@ -0,0 +1,22 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzCustomProviderAssociation.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzCustomProviderAssociation' { + It 'Delete' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'DeleteViaIdentity' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/Set-AzCustomProviderAssociation.Tests.ps1 b/src/CustomProviders/test/Set-AzCustomProviderAssociation.Tests.ps1 new file mode 100644 index 000000000000..a557287e9dd4 --- /dev/null +++ b/src/CustomProviders/test/Set-AzCustomProviderAssociation.Tests.ps1 @@ -0,0 +1,18 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Set-AzCustomProviderAssociation.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-AzCustomProviderAssociation' { + It 'UpdateExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/Update-AzCustomProvider.Tests.ps1 b/src/CustomProviders/test/Update-AzCustomProvider.Tests.ps1 new file mode 100644 index 000000000000..25c0dd741541 --- /dev/null +++ b/src/CustomProviders/test/Update-AzCustomProvider.Tests.ps1 @@ -0,0 +1,22 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Update-AzCustomProvider.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 'Update-AzCustomProvider' { + It 'UpdateExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } + + It 'UpdateViaIdentityExpanded' -skip { + { throw [System.NotImplementedException] } | Should -Not -Throw + } +} diff --git a/src/CustomProviders/test/env.json b/src/CustomProviders/test/env.json new file mode 100644 index 000000000000..782dd557f8d2 --- /dev/null +++ b/src/CustomProviders/test/env.json @@ -0,0 +1,6 @@ +{ + "Tenant": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "CustomProvider": "MSTest.MyTesth2niy", + "ResourceGroup": "rgdsw53", + "SubscriptionId": "c9cbd920-c00c-427c-852b-8aaf38badaeb" +} diff --git a/src/CustomProviders/test/loadEnv.ps1 b/src/CustomProviders/test/loadEnv.ps1 new file mode 100644 index 000000000000..c4ebf2e8310c --- /dev/null +++ b/src/CustomProviders/test/loadEnv.ps1 @@ -0,0 +1,28 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:SubscriptionId"=$env.SubscriptionId; "*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/src/CustomProviders/test/localEnv.json b/src/CustomProviders/test/localEnv.json new file mode 100644 index 000000000000..bbf7a741b6c7 --- /dev/null +++ b/src/CustomProviders/test/localEnv.json @@ -0,0 +1,6 @@ +{ + "ResourceGroup": "rgpldg7", + "SubscriptionId": "c9cbd920-c00c-427c-852b-8aaf38badaeb", + "Tenant": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "CustomProvider": "MSTest.MyTest28lfc" +} diff --git a/src/CustomProviders/test/readme.md b/src/CustomProviders/test/readme.md new file mode 100644 index 000000000000..7c752b4c8c43 --- /dev/null +++ b/src/CustomProviders/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/CustomProviders/test/utils.ps1 b/src/CustomProviders/test/utils.ps1 new file mode 100644 index 000000000000..b82ad3eb9ccb --- /dev/null +++ b/src/CustomProviders/test/utils.ps1 @@ -0,0 +1,33 @@ +function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + $rg1 = ("rg" + (RandomString $false 5)) + $name1 = ("MSTest.MyTest" + (RandomString $false 5)) + New-AzResourceGroup -Name $rg1 -Location "West US" | Out-Null + # For any resources you created for test, you should add it to $env here. + $env['ResourceGroup'] = $rg1 + $env['CustomProvider'] = $name1 + $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 + if ($env.ResourceGroup -ne $null) + { + Remove-AzResourceGroup -Name $env.ResourceGroup | Out-Null + } +} + diff --git a/src/HanaOnAzure/Az.HanaOnAzure.csproj b/src/HanaOnAzure/Az.HanaOnAzure.csproj new file mode 100644 index 000000000000..99877a72a96a --- /dev/null +++ b/src/HanaOnAzure/Az.HanaOnAzure.csproj @@ -0,0 +1,7 @@ + + + HanaOnAzure + + + + \ No newline at end of file diff --git a/src/HanaOnAzure/Az.HanaOnAzure.format.ps1xml b/src/HanaOnAzure/Az.HanaOnAzure.format.ps1xml new file mode 100644 index 000000000000..e390fceecd06 --- /dev/null +++ b/src/HanaOnAzure/Az.HanaOnAzure.format.ps1xml @@ -0,0 +1,1495 @@ + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.HanaOnAzureIdentity + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.HanaOnAzureIdentity + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Location + + + OperationKind + + + ProviderInstanceName + + + ResourceGroupName + + + ResourceName + + + SapMonitorName + + + Scope + + + SubscriptionId + + + VaultName + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Display + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Display + + + + + + + + + + + + + + + + + + + + + + + + Description + + + Operation + + + Origin + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse + + + + + + + + + + + + + + + Code + + + Message + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Operation + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Operation + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstance + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstance + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceListResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceProperties + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceProperties + + + + + + + + + + + + + + + + + + + + + Metadata + + + Property + + + ProvisioningState + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitor + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitor + + + + + + + + + + + + + + + Name + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorListResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorProperties + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorProperties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + EnableCustomerAnalytic + + + LogAnalyticsWorkspaceArmId + + + LogAnalyticsWorkspaceId + + + LogAnalyticsWorkspaceSharedKey + + + ManagedResourceGroupName + + + MonitorSubnet + + + ProvisioningState + + + SapMonitorCollectorVersion + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags1 + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags1 + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBody + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBody + + + + + + + + + + + + + + + + + + Code + + + Message + + + Target + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdate + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdate + + + + + + + + + + + + + + + + + + Name + + + Type + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdateTags + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdateTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Operation + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Operation + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationDisplay + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationDisplay + + + + + + + + + + + + + + + + + + + + + Description + + + Operation + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationListResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentity + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentity + + + + + + + + + + + + + + + + + + Name + + + Type + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityProperties + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityProperties + + + + + + + + + + + + + + + + + + + + + ClientId + + + ClientSecretUrl + + + PrincipalId + + + TenantId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityTags + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentitiesListResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentitiesListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties + + + + + + + + + + + + + + + + + + ClientId + + + PrincipalId + + + TenantId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntry + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntry + + + + + + + + + + + + + + + + + + ApplicationId + + + ObjectId + + + TenantId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.CheckNameAvailabilityResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.CheckNameAvailabilityResult + + + + + + + + + + + + + + + + + + Message + + + NameAvailable + + + Reason + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVault + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVault + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultListResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultProperties + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultProperties + + + + + + + + + + + + + + + + + + + + + DeletionDate + + + Location + + + ScheduledPurgeDate + + + VaultId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTags + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Permissions + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Permissions + + + + + + + + + + + + + + + + + + + + + Certificate + + + Key + + + Secret + + + Storage + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Resource + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Resource + + + + + + + + + + + + + + + + + + Name + + + Type + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceListResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTags + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku + + + + + + + + + + + + + + + Family + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyParameters + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyParameters + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCheckNameAvailabilityParameters + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCheckNameAvailabilityParameters + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParameters + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParameters + + + + + + + + + + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParametersTags + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParametersTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultListResult + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultListResult + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchParametersTags + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchParametersTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchProperties + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchProperties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CreateMode + + + EnablePurgeProtection + + + EnableSoftDelete + + + EnabledForDeployment + + + EnabledForDiskEncryption + + + EnabledForTemplateDeployment + + + TenantId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CreateMode + + + EnablePurgeProtection + + + EnableSoftDelete + + + EnabledForDeployment + + + EnabledForDiskEncryption + + + EnabledForTemplateDeployment + + + TenantId + + + VaultUri + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ProxyResource + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ProxyResource + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResource + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResource + + + + + + + + + + + + + + + + + + Name + + + Type + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTags + + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTags + + + + + + + + + + + + Item + + + + + + + + \ No newline at end of file diff --git a/src/HanaOnAzure/Az.HanaOnAzure.psd1 b/src/HanaOnAzure/Az.HanaOnAzure.psd1 new file mode 100644 index 000000000000..075543544c24 --- /dev/null +++ b/src/HanaOnAzure/Az.HanaOnAzure.psd1 @@ -0,0 +1,25 @@ +@{ + GUID = '79ad50da-e6b5-4703-885a-d36974a4d9b9' + RootModule = './Az.HanaOnAzure.psm1' + ModuleVersion = '0.1.0' + CompatiblePSEditions = 'Core', 'Desktop' + Author = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' + Copyright = 'Microsoft Corporation. All rights reserved.' + Description = 'Microsoft Azure PowerShell: HanaOn cmdlets' + PowerShellVersion = '5.1' + DotNetFrameworkVersion = '4.7.2' + RequiredAssemblies = './bin/Az.HanaOnAzure.private.dll' + RequiredModules = @(@{ModuleName = 'Az.Accounts'; ModuleVersion = '1.9.0'; }) + FormatsToProcess = './Az.HanaOnAzure.format.ps1xml' + FunctionsToExport = 'Get-AzSapMonitor', 'Get-AzSapMonitorProviderInstance', 'New-AzSapMonitor', 'New-AzSapMonitorProviderInstance', 'Remove-AzSapMonitor', 'Remove-AzSapMonitorProviderInstance', 'Update-AzSapMonitor' + AliasesToExport = '*' + PrivateData = @{ + PSData = @{ + Tags = 'Azure', 'ResourceManager', 'ARM', 'PSModule', 'HanaOn' + LicenseUri = 'https://aka.ms/azps-license' + ProjectUri = 'https://github.com/Azure/azure-powershell' + ReleaseNotes = '* the first preview release' + } + } +} diff --git a/src/HanaOnAzure/Az.HanaOnAzure.psm1 b/src/HanaOnAzure/Az.HanaOnAzure.psm1 new file mode 100644 index 000000000000..f6b9787ac48c --- /dev/null +++ b/src/HanaOnAzure/Az.HanaOnAzure.psm1 @@ -0,0 +1,109 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # + # Copyright Microsoft Corporation + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # http://www.apache.org/licenses/LICENSE-2.0 + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'1.8.1' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 1.8.1 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 1.8.1 or greater. For installation instructions, please see: https://docs.microsoft.com/en-us/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'1.8.1') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 1.8.1 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to remove '.PSSharedModules' in your home directory. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.HanaOnAzure.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.HanaOnAzure.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/HanaOnAzure/ChangeLog.md b/src/HanaOnAzure/ChangeLog.md new file mode 100644 index 000000000000..b76ecb79cf4a --- /dev/null +++ b/src/HanaOnAzure/ChangeLog.md @@ -0,0 +1,24 @@ + +## Upcoming Release + +## Version 0.1.0 +* the first preview release + diff --git a/src/HanaOnAzure/HanaOnAzure.sln b/src/HanaOnAzure/HanaOnAzure.sln new file mode 100644 index 000000000000..872cbda7b447 --- /dev/null +++ b/src/HanaOnAzure/HanaOnAzure.sln @@ -0,0 +1,48 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Accounts", "..\Accounts\Accounts\Accounts.csproj", "{142D7B0B-388A-4CEB-A228-7F6D423C5C2E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication", "..\Accounts\Authentication\Authentication.csproj", "{62843FE6-7575-4D88-B989-7DF7EEC0BC01}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication.ResourceManager", "..\Accounts\Authentication.ResourceManager\Authentication.ResourceManager.csproj", "{442C609B-A431-4A71-B289-08F0B63C83E5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authenticators", "..\Accounts\Authenticators\Authenticators.csproj", "{59E8F6B8-8F0E-403F-B88B-9736DBC396D9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Az.HanaOnAzure", "Az.HanaOnAzure.csproj", "{77394AC9-9E20-4407-8287-B068C402EF3B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.Build.0 = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.Build.0 = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.Build.0 = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.Build.0 = Release|Any CPU + {77394AC9-9E20-4407-8287-B068C402EF3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {77394AC9-9E20-4407-8287-B068C402EF3B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {77394AC9-9E20-4407-8287-B068C402EF3B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {77394AC9-9E20-4407-8287-B068C402EF3B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F9B3D96E-9680-40BE-A917-02EE655D6030} + EndGlobalSection +EndGlobal diff --git a/src/HanaOnAzure/MSSharedLibKey.snk b/src/HanaOnAzure/MSSharedLibKey.snk new file mode 100644 index 000000000000..695f1b38774e Binary files /dev/null and b/src/HanaOnAzure/MSSharedLibKey.snk differ diff --git a/src/HanaOnAzure/Properties/AssemblyInfo.cs b/src/HanaOnAzure/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..5e2f5513894f --- /dev/null +++ b/src/HanaOnAzure/Properties/AssemblyInfo.cs @@ -0,0 +1,28 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Microsoft Azure Powershell - HanaOnAzure")] +[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] +[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] +[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] + +[assembly: ComVisible(false)] +[assembly: CLSCompliant(false)] +[assembly: Guid("1A2AE489-381B-47BF-91F0-99B42E4FC28B")] +[assembly: AssemblyVersion("0.1.0")] +[assembly: AssemblyFileVersion("0.1.0")] \ No newline at end of file diff --git a/src/HanaOnAzure/build-module.ps1 b/src/HanaOnAzure/build-module.ps1 new file mode 100644 index 000000000000..0acd0a74494a --- /dev/null +++ b/src/HanaOnAzure/build-module.ps1 @@ -0,0 +1,153 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $Isolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.HanaOnAzure' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: HanaOn cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.HanaOnAzure.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/src/HanaOnAzure/check-dependencies.ps1 b/src/HanaOnAzure/check-dependencies.ps1 new file mode 100644 index 000000000000..513c52ca2fb5 --- /dev/null +++ b/src/HanaOnAzure/check-dependencies.ps1 @@ -0,0 +1,64 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [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)) { + $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 '1.8.1' +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))) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest-beta .\readme.md --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/src/HanaOnAzure/custom/Az.HanaOnAzure.custom.psm1 b/src/HanaOnAzure/custom/Az.HanaOnAzure.custom.psm1 new file mode 100644 index 000000000000..f4368ef7194b --- /dev/null +++ b/src/HanaOnAzure/custom/Az.HanaOnAzure.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.HanaOnAzure.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.HanaOnAzure.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/HanaOnAzure/custom/New-AzSapMonitorProviderInstance.ps1 b/src/HanaOnAzure/custom/New-AzSapMonitorProviderInstance.ps1 new file mode 100644 index 000000000000..e2fbe8133e17 --- /dev/null +++ b/src/HanaOnAzure/custom/New-AzSapMonitorProviderInstance.ps1 @@ -0,0 +1,271 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hana/new-azsapproviderinstance +#> +function New-AzSapMonitorProviderInstance { + [OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance])] + [CmdletBinding(DefaultParameterSetName = 'ByString', PositionalBinding = $false, SupportsShouldProcess, ConfirmImpact = 'Medium')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', 'HanaDatabasePasswordKeyVaultResourceId', Justification = 'Not a password')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', 'HanaDatabasePasswordSecretId', Justification = 'Not a password')] + param( + [Parameter(Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script = '(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Collections.Hashtable] + # A JSON string containing metadata of the provider instance. + ${Metadata}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The type of provider instance. Supported values are: "SapHana". + ${ProviderType}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The hostname of SAP HANA instance. + ${HanaHostname}, + + [Parameter(Mandatory)] + [Alias('HanaDbName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The database name of SAP HANA instance. + ${HanaDatabaseName}, + + [Parameter(Mandatory)] + [Alias('HanaDbSqlPort')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Int32] + # The SQL port of the database of SAP HANA instance. + ${HanaDatabaseSqlPort}, + + [Parameter(Mandatory)] + [Alias('HanaDbUsername')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The username of the database of SAP HANA instance. + ${HanaDatabaseUsername}, + + [Parameter(ParameterSetName = 'ByString', Mandatory)] + [Alias('HanaDbPassword')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [SecureString] + # The password of the database of SAP HANA instance. + ${HanaDatabasePassword}, + + [Parameter(ParameterSetName = 'ByKeyVault', Mandatory)] + [Alias('HanaDbPasswordKeyVaultId', 'KeyVaultId')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # Resource ID of the Key Vault that contains the HANA credentials. + ${HanaDatabasePasswordKeyVaultResourceId}, + + [Parameter(ParameterSetName = 'ByKeyVault', Mandatory)] + [Alias('HanaDbPasswordSecretId', 'SecretId')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # Secret identifier to the Key Vault secret that contains the HANA credentials. + ${HanaDatabasePasswordSecretId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} + ) + + process { + $null = $PSBoundParameters.Remove('ResourceGroupName') + $null = $PSBoundParameters.Remove('Name') + $null = $PSBoundParameters.Remove('SapMonitorName') + $null = $PSBoundParameters.Remove('ProviderType') + $null = $PSBoundParameters.Remove('Metadata') + + $null = $PSBoundParameters.Remove('HanaHostname') + $null = $PSBoundParameters.Remove('HanaDatabaseName') + $null = $PSBoundParameters.Remove('HanaDatabaseSqlPort') + $null = $PSBoundParameters.Remove('HanaDatabaseUsername') + $null = $PSBoundParameters.Remove('HanaDatabasePasswordSecretId') + $null = $PSBoundParameters.Remove('HanaDatabasePasswordKeyVaultResourceId') + + $null = $PSBoundParameters.Remove('Confirm') + $null = $PSBoundParameters.Remove('WhatIf') + $hasAsJob = $PSBoundParameters.Remove('AsJob') + + $parameterSet = $PSCmdlet.ParameterSetName + switch ($parameterSet) { + 'ByString' { + $null = $PSBoundParameters.Remove('HanaDatabasePassword') + $property = @{ + hanaHostname = $HanaHostname + hanaDbName = $HanaDatabaseName + hanaDbSqlPort = $HanaDatabaseSqlPort + hanaDbUsername = $HanaDatabaseUsername + hanaDbPassword = ConvertFrom-SecureString $HanaDatabasePassword -AsPlainText + } + } + 'ByKeyVault' { + # Referencing to CLI's implementation + # https://github.com/Azure/azure-hanaonazure-cli-extension/blob/master/azext_hanaonazure/custom.py#L312-L338 + + # 1. Get MSI + $sapMonitor = Get-AzSapMonitor -ResourceGroupName $ResourceGroupName -Name $SapMonitorName @PSBoundParameters + $managedResourceGroupName = $sapMonitor.ManagedResourceGroupName + $sapMonitorId = $managedResourceGroupName.Split("-")[2] + + $msiName = "sapmon-msi-$sapMonitorId" + $msi = Az.HanaOnAzure.internal\Get-AzUserAssignedIdentity -ResourceGroupName $managedResourceGroupName -ResourceName $msiName @PSBoundParameters + + # 2. Grant key vault access to MSI + $null = $HanaDatabasePasswordKeyVaultResourceId -match "^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.KeyVault/vaults/(?[^/]+)$" + $vaultSubscriptionId = $Matches['subscriptionId'] + $vaultResourceGroupName = $Matches['resourceGroupName'] + $vaultName = $Matches['vaultName'] + + # Need to use vault's sub ID, not the sub ID of this cmdlet + $null = $PSBoundParameters.Remove('SubscriptionId') + $null = Az.HanaOnAzure.internal\Set-AzVaultAccessPolicy -OperationKind add -ResourceGroupName $vaultResourceGroupName -VaultName $vaultName -SubscriptionId $vaultSubscriptionId -AccessPolicy @{ + ObjectId = $msi.PrincipalId + TenantId = (Get-AzContext).Tenant.Id + PermissionSecret = 'get' + } @PSBoundParameters + $PSBoundParameters.Add('SubscriptionId', $SubscriptionId) + + # Service accepts secret ID without port + # but (Get-AzKeyVaultSecret).Id contains port (":443") + # need to remove it + $vaultPort = ":443" + if ($HanaDatabasePasswordSecretId.Contains($vaultPort)) { + $HanaDatabasePasswordSecretId = $HanaDatabasePasswordSecretId.Replace($vaultPort, "") + } + + $property = @{ + hanaHostname = $HanaHostname + hanaDbName = $HanaDatabaseName + hanaDbSqlPort = $HanaDatabaseSqlPort + hanaDbUsername = $HanaDatabaseUsername + hanaDbPasswordKeyVaultUrl = $HanaDatabasePasswordSecretId + keyVaultId = $HanaDatabasePasswordKeyVaultResourceId # key vault id is keyvault resource id + keyVaultCredentialsMsiClientID = $msi.ClientId # FIXME: this property is not needed in newer service backend, can we remove it? + } + } + } + $PSBoundParameters.Add('ResourceGroupName', $ResourceGroupName) + $PSBoundParameters.Add('Name', $Name) + $PSBoundParameters.Add('SapMonitorName', $SapMonitorName) + $PSBoundParameters.Add('ProviderType', $ProviderType) + $PSBoundParameters.Add('Metadata', ($Metadata | ConvertTo-Json)) + + $PSBoundParameters.Add('ProviderInstanceProperty', ($property | ConvertTo-Json)) + + if ($hasAsJob) { + $PSBoundParameters.Add('AsJob', $true) + } + + if ($PSCmdlet.ShouldProcess("SAP monitor provider instance $Name", "Create")) { + Az.HanaOnAzure.internal\New-AzSapMonitorProviderInstance @PSBoundParameters + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/custom/readme.md b/src/HanaOnAzure/custom/readme.md new file mode 100644 index 000000000000..965eec748478 --- /dev/null +++ b/src/HanaOnAzure/custom/readme.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.HanaOnAzure` 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.HanaOnAzure.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.HanaOnAzure` 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.HanaOnAzure.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.HanaOnAzure.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundemental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.HanaOnAzure`. 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.HanaOnAzure.Models.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propegated to reference documentation via [help comments](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.HanaOnAzure`. +- `Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.HanaOnAzure`. For more information, see [readme.md](..\internal/readme.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.ProfileAttribute` + - Used in C# and script cmdlets to define which Azure profiles the cmdlet supports. This is only supported for Azure (`--azure`) modules. \ No newline at end of file diff --git a/src/HanaOnAzure/examples/Get-AzSapMonitor.md b/src/HanaOnAzure/examples/Get-AzSapMonitor.md new file mode 100644 index 000000000000..413067132225 --- /dev/null +++ b/src/HanaOnAzure/examples/Get-AzSapMonitor.md @@ -0,0 +1,48 @@ +### Example 1: Get all SAP monitors under a subscription +```powershell +PS C:\> Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets SAP monitors under a subscription. + +### Example 2: Get a SAP monitor by name +```powershell +PS C:\> Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets a SAP monitor by name. + +### Example 3: Get a SAP monitor by object +```powershell +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 +PS C:\> Get-AzSapMonitor -InputObject $sap + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets a SAP monitor by object. + +### Example 4: Get a SAP monitor by pipeline +```powershell +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01'} | Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets a SAP monitor by pipeline. + + + diff --git a/src/HanaOnAzure/examples/Get-AzSapMonitorProviderInstance.md b/src/HanaOnAzure/examples/Get-AzSapMonitorProviderInstance.md new file mode 100644 index 000000000000..c75e1a32275d --- /dev/null +++ b/src/HanaOnAzure/examples/Get-AzSapMonitorProviderInstance.md @@ -0,0 +1,46 @@ +### Example 1: Get all instances under a SAP monitor +```powershell +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets all instances under a SAP monitor. + +### Example 2: Get an instances of SAP monitor by name +```powershell +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets an instances of SAP monitor by name. + +### Example 3: Get an instances of SAP monitor by object +```powershell +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 +PS C:\> Get-AzSapMonitorProviderInstance -InputObject $sapIns + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets an instances of SAP monitor by object. + +### Example 4: Get an instances of SAP monitor by pipeline +```powershell +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01/providerInstances/ps-sapmonitorins-t02"} | Get-AzSapMonitorProviderInstance + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets an instances of SAP monitor by pipeline. + diff --git a/src/HanaOnAzure/examples/New-AzSapMonitor.md b/src/HanaOnAzure/examples/New-AzSapMonitor.md new file mode 100644 index 000000000000..e0f808aca0db --- /dev/null +++ b/src/HanaOnAzure/examples/New-AzSapMonitor.md @@ -0,0 +1,13 @@ +### Example 1: New SAP monitor +```powershell +PS C:\> $workspace = New-AzOperationalInsightsWorkspace -ResourceGroupName nancyc-hn1 -Name sapmonitor-test -Location westus2 -Sku "Standard" +PS C:\> $workspace = Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName nancyc-hn1 -Name sapmonitor-test +PS C:\> New-AzSapMonitor -Name ps-sapmonitor-t01 -ResourceGroupName nancyc-hn1 -Location westus2 -EnableCustomerAnalytic -MonitorSubnet "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin" -LogAnalyticsWorkspaceSharedKey $workspace.PrimarySharedKey -LogAnalyticsWorkspaceId $workspace.CustomerId -LogAnalyticsWorkspaceResourceId $workspace.ResourceId + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command creates a SAP monitor. + diff --git a/src/HanaOnAzure/examples/New-AzSapMonitorProviderInstance.md b/src/HanaOnAzure/examples/New-AzSapMonitorProviderInstance.md new file mode 100644 index 000000000000..36d4d905bf26 --- /dev/null +++ b/src/HanaOnAzure/examples/New-AzSapMonitorProviderInstance.md @@ -0,0 +1,22 @@ +### Example 1: Create an instance of SAP monitor by string for HANA +```powershell +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -Name ps-sapmonitorins-t01 -SapMonitorName yemingmonitor -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command creates an instance of SAP monitor by string for HANA. + +### Example 2: Create an instance of SAP monitor by key vault for HANA +```powershell +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName sapMonitor-vayh7q-test -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId https://kv-9gosjc-test.vault.azure.net/secrets/hanaPassword/bf516d1dfcc144138e5cf55114f3344b -HanaDatabasePasswordKeyVaultResourceId /subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-8p50xe/providers/Microsoft.KeyVault/vaults/kv-9gosjc-test -Name sapins-kv-test + +Name Type +---- ---- +sapins-kv-test Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command creates an instance of SAP monitor by key vault for HANA. + diff --git a/src/HanaOnAzure/examples/Remove-AzSapMonitor.md b/src/HanaOnAzure/examples/Remove-AzSapMonitor.md new file mode 100644 index 000000000000..99704f4df816 --- /dev/null +++ b/src/HanaOnAzure/examples/Remove-AzSapMonitor.md @@ -0,0 +1,17 @@ +### Example 1: Remove a SAP monitor by name +```powershell +PS C:\> Remove-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t02 + +``` + +This command removes a SAP monitor by name. + +### Example 2: Remove a SAP monitor by object +```powershell +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Remove-AzSapMonitor -InputObject $sap + +``` + +This command removes a SAP monitor by object. + diff --git a/src/HanaOnAzure/examples/Remove-AzSapMonitorProviderInstance.md b/src/HanaOnAzure/examples/Remove-AzSapMonitorProviderInstance.md new file mode 100644 index 000000000000..3cac2a001399 --- /dev/null +++ b/src/HanaOnAzure/examples/Remove-AzSapMonitorProviderInstance.md @@ -0,0 +1,17 @@ +### Example 1: Remove instance of SAP monitor by name +```powershell +PS C:\> Remove-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +``` + +This command removes instance of SAP monitor by name. + +### Example 2: Remove instance of SAP monitor by object +```powershell +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t01 +PS C:\> Remove-AzSapMonitorProviderInstance -InputObject $sapIns + +``` + +This command removes instance of SAP monitor by object. + diff --git a/src/HanaOnAzure/examples/Update-AzSapMonitor.md b/src/HanaOnAzure/examples/Update-AzSapMonitor.md new file mode 100644 index 000000000000..95217aaf3172 --- /dev/null +++ b/src/HanaOnAzure/examples/Update-AzSapMonitor.md @@ -0,0 +1,23 @@ +### Example 1: Update a SAP monitor by name +```powershell +PS C:\> Update-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This commands updates a SAP monitor by name. + +### Example 2: Update a SAP monitor by object +```powershell +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Update-AzSapMonitor -InputObject $sap -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This commands updates a SAP monitor by object. + diff --git a/src/HanaOnAzure/export-surface.ps1 b/src/HanaOnAzure/export-surface.ps1 new file mode 100644 index 000000000000..a08aac945356 --- /dev/null +++ b/src/HanaOnAzure/export-surface.ps1 @@ -0,0 +1,40 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.HanaOnAzure.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.HanaOnAzure' +$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/HanaOnAzure/exports/Get-AzSapMonitor.ps1 b/src/HanaOnAzure/exports/Get-AzSapMonitor.ps1 new file mode 100644 index 000000000000..205e1b54856d --- /dev/null +++ b/src/HanaOnAzure/exports/Get-AzSapMonitor.ps1 @@ -0,0 +1,191 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. +.Description +Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. +.Example +PS C:\> Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 +PS C:\> Get-AzSapMonitor -InputObject $sap + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01'} | Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azsapmonitor +#> +function Get-AzSapMonitor { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.HanaOnAzure.private\Get-AzSapMonitor_Get'; + GetViaIdentity = 'Az.HanaOnAzure.private\Get-AzSapMonitor_GetViaIdentity'; + List = 'Az.HanaOnAzure.private\Get-AzSapMonitor_List'; + } + if (('Get', 'List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/Get-AzSapMonitorProviderInstance.ps1 b/src/HanaOnAzure/exports/Get-AzSapMonitorProviderInstance.ps1 new file mode 100644 index 000000000000..2fbdb29ed9a8 --- /dev/null +++ b/src/HanaOnAzure/exports/Get-AzSapMonitorProviderInstance.ps1 @@ -0,0 +1,199 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 +PS C:\> Get-AzSapMonitorProviderInstance -InputObject $sapIns + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01/providerInstances/ps-sapmonitorins-t02"} | Get-AzSapMonitorProviderInstance + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azsapmonitorproviderinstance +#> +function Get-AzSapMonitorProviderInstance { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.HanaOnAzure.private\Get-AzSapMonitorProviderInstance_Get'; + GetViaIdentity = 'Az.HanaOnAzure.private\Get-AzSapMonitorProviderInstance_GetViaIdentity'; + List = 'Az.HanaOnAzure.private\Get-AzSapMonitorProviderInstance_List'; + } + if (('Get', 'List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/New-AzSapMonitor.ps1 b/src/HanaOnAzure/exports/New-AzSapMonitor.ps1 new file mode 100644 index 000000000000..68e89b6a31e2 --- /dev/null +++ b/src/HanaOnAzure/exports/New-AzSapMonitor.ps1 @@ -0,0 +1,201 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a SAP monitor for the specified subscription, resource group, and resource name. +.Description +Creates a SAP monitor for the specified subscription, resource group, and resource name. +.Example +PS C:\> $workspace = New-AzOperationalInsightsWorkspace -ResourceGroupName nancyc-hn1 -Name sapmonitor-test -Location westus2 -Sku "Standard" +PS C:\> $workspace = Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName nancyc-hn1 -Name sapmonitor-test +PS C:\> New-AzSapMonitor -Name ps-sapmonitor-t01 -ResourceGroupName nancyc-hn1 -Location westus2 -EnableCustomerAnalytic -MonitorSubnet "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin" -LogAnalyticsWorkspaceSharedKey $workspace.PrimarySharedKey -LogAnalyticsWorkspaceId $workspace.CustomerId -LogAnalyticsWorkspaceResourceId $workspace.ResourceId + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azsapmonitor +#> +function New-AzSapMonitor { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Management.Automation.SwitchParameter] + # The value indicating whether to send analytics to Microsoft + ${EnableCustomerAnalytic}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The workspace ID of the log analytics workspace to be used for monitoring + ${LogAnalyticsWorkspaceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The ARM ID of the Log Analytics Workspace that is used for monitoring + ${LogAnalyticsWorkspaceResourceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The shared key of the log analytics workspace that is used for monitoring + ${LogAnalyticsWorkspaceSharedKey}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The subnet which the SAP monitor will be deployed in. + # It should be the same subnet of HANA database. + ${MonitorSubnetResourceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.HanaOnAzure.private\New-AzSapMonitor_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/New-AzSapMonitorProviderInstance.ps1 b/src/HanaOnAzure/exports/New-AzSapMonitorProviderInstance.ps1 new file mode 100644 index 000000000000..9b014e473653 --- /dev/null +++ b/src/HanaOnAzure/exports/New-AzSapMonitorProviderInstance.ps1 @@ -0,0 +1,229 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -Name ps-sapmonitorins-t01 -SapMonitorName yemingmonitor -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName sapMonitor-vayh7q-test -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId https://kv-9gosjc-test.vault.azure.net/secrets/hanaPassword/bf516d1dfcc144138e5cf55114f3344b -HanaDatabasePasswordKeyVaultResourceId /subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-8p50xe/providers/Microsoft.KeyVault/vaults/kv-9gosjc-test -Name sapins-kv-test + +Name Type +---- ---- +sapins-kv-test Microsoft.HanaOnAzure/sapMonitors/providerInstances + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hana/new-azsapproviderinstance +#> +function New-AzSapMonitorProviderInstance { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance])] +[CmdletBinding(DefaultParameterSetName='ByString', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The type of provider instance. + # Supported values are: "SapHana". + ${ProviderType}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The hostname of SAP HANA instance. + ${HanaHostname}, + + [Parameter(Mandatory)] + [Alias('HanaDbName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The database name of SAP HANA instance. + ${HanaDatabaseName}, + + [Parameter(Mandatory)] + [Alias('HanaDbSqlPort')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Int32] + # The SQL port of the database of SAP HANA instance. + ${HanaDatabaseSqlPort}, + + [Parameter(Mandatory)] + [Alias('HanaDbUsername')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The username of the database of SAP HANA instance. + ${HanaDatabaseUsername}, + + [Parameter(ParameterSetName='ByString', Mandatory)] + [Alias('HanaDbPassword')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Security.SecureString] + # The password of the database of SAP HANA instance. + ${HanaDatabasePassword}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Collections.Hashtable] + # A JSON string containing metadata of the provider instance. + ${Metadata}, + + [Parameter(ParameterSetName='ByKeyVault', Mandatory)] + [Alias('HanaDbPasswordKeyVaultId', 'KeyVaultId')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # Resource ID of the Key Vault that contains the HANA credentials. + ${HanaDatabasePasswordKeyVaultResourceId}, + + [Parameter(ParameterSetName='ByKeyVault', Mandatory)] + [Alias('HanaDbPasswordSecretId', 'SecretId')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # Secret identifier to the Key Vault secret that contains the HANA credentials. + ${HanaDatabasePasswordSecretId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 = @{ + ByString = 'Az.HanaOnAzure.custom\New-AzSapMonitorProviderInstance'; + ByKeyVault = 'Az.HanaOnAzure.custom\New-AzSapMonitorProviderInstance'; + } + if (('ByString', 'ByKeyVault') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/ProxyCmdletDefinitions.ps1 b/src/HanaOnAzure/exports/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..84efb756ea1c --- /dev/null +++ b/src/HanaOnAzure/exports/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,1385 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 +PS C:\> Get-AzSapMonitorProviderInstance -InputObject $sapIns + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01/providerInstances/ps-sapmonitorins-t02"} | Get-AzSapMonitorProviderInstance + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azsapmonitorproviderinstance +#> +function Get-AzSapMonitorProviderInstance { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.HanaOnAzure.private\Get-AzSapMonitorProviderInstance_Get'; + GetViaIdentity = 'Az.HanaOnAzure.private\Get-AzSapMonitorProviderInstance_GetViaIdentity'; + List = 'Az.HanaOnAzure.private\Get-AzSapMonitorProviderInstance_List'; + } + if (('Get', 'List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. +.Description +Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. +.Example +PS C:\> Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 +PS C:\> Get-AzSapMonitor -InputObject $sap + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01'} | Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azsapmonitor +#> +function Get-AzSapMonitor { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.HanaOnAzure.private\Get-AzSapMonitor_Get'; + GetViaIdentity = 'Az.HanaOnAzure.private\Get-AzSapMonitor_GetViaIdentity'; + List = 'Az.HanaOnAzure.private\Get-AzSapMonitor_List'; + } + if (('Get', 'List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a SAP monitor for the specified subscription, resource group, and resource name. +.Description +Creates a SAP monitor for the specified subscription, resource group, and resource name. +.Example +PS C:\> $workspace = New-AzOperationalInsightsWorkspace -ResourceGroupName nancyc-hn1 -Name sapmonitor-test -Location westus2 -Sku "Standard" +PS C:\> $workspace = Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName nancyc-hn1 -Name sapmonitor-test +PS C:\> New-AzSapMonitor -Name ps-sapmonitor-t01 -ResourceGroupName nancyc-hn1 -Location westus2 -EnableCustomerAnalytic -MonitorSubnet "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin" -LogAnalyticsWorkspaceSharedKey $workspace.PrimarySharedKey -LogAnalyticsWorkspaceId $workspace.CustomerId -LogAnalyticsWorkspaceResourceId $workspace.ResourceId + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azsapmonitor +#> +function New-AzSapMonitor { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Management.Automation.SwitchParameter] + # The value indicating whether to send analytics to Microsoft + ${EnableCustomerAnalytic}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The workspace ID of the log analytics workspace to be used for monitoring + ${LogAnalyticsWorkspaceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The ARM ID of the Log Analytics Workspace that is used for monitoring + ${LogAnalyticsWorkspaceResourceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The shared key of the log analytics workspace that is used for monitoring + ${LogAnalyticsWorkspaceSharedKey}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The subnet which the SAP monitor will be deployed in. + # It should be the same subnet of HANA database. + ${MonitorSubnetResourceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.HanaOnAzure.private\New-AzSapMonitor_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> Remove-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +.Example +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t01 +PS C:\> Remove-AzSapMonitorProviderInstance -InputObject $sapIns + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azsapmonitorproviderinstance +#> +function Remove-AzSapMonitorProviderInstance { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.HanaOnAzure.private\Remove-AzSapMonitorProviderInstance_Delete'; + DeleteViaIdentity = 'Az.HanaOnAzure.private\Remove-AzSapMonitorProviderInstance_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes a SAP monitor with the specified subscription, resource group, and monitor name. +.Description +Deletes a SAP monitor with the specified subscription, resource group, and monitor name. +.Example +PS C:\> Remove-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t02 + +.Example +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Remove-AzSapMonitor -InputObject $sap + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azsapmonitor +#> +function Remove-AzSapMonitor { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.HanaOnAzure.private\Remove-AzSapMonitor_Delete'; + DeleteViaIdentity = 'Az.HanaOnAzure.private\Remove-AzSapMonitor_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. +.Description +Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. +.Example +PS C:\> Update-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Update-AzSapMonitor -InputObject $sap -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/update-azsapmonitor +#> +function Update-AzSapMonitor { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1]))] + [System.Collections.Hashtable] + # Tags field of the resource. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Update-AzSapMonitor_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.HanaOnAzure.private\Update-AzSapMonitor_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -Name ps-sapmonitorins-t01 -SapMonitorName yemingmonitor -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName sapMonitor-vayh7q-test -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId https://kv-9gosjc-test.vault.azure.net/secrets/hanaPassword/bf516d1dfcc144138e5cf55114f3344b -HanaDatabasePasswordKeyVaultResourceId /subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-8p50xe/providers/Microsoft.KeyVault/vaults/kv-9gosjc-test -Name sapins-kv-test + +Name Type +---- ---- +sapins-kv-test Microsoft.HanaOnAzure/sapMonitors/providerInstances + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hana/new-azsapproviderinstance +#> +function New-AzSapMonitorProviderInstance { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance])] +[CmdletBinding(DefaultParameterSetName='ByString', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The type of provider instance. + # Supported values are: "SapHana". + ${ProviderType}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The hostname of SAP HANA instance. + ${HanaHostname}, + + [Parameter(Mandatory)] + [Alias('HanaDbName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The database name of SAP HANA instance. + ${HanaDatabaseName}, + + [Parameter(Mandatory)] + [Alias('HanaDbSqlPort')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Int32] + # The SQL port of the database of SAP HANA instance. + ${HanaDatabaseSqlPort}, + + [Parameter(Mandatory)] + [Alias('HanaDbUsername')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The username of the database of SAP HANA instance. + ${HanaDatabaseUsername}, + + [Parameter(ParameterSetName='ByString', Mandatory)] + [Alias('HanaDbPassword')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Security.SecureString] + # The password of the database of SAP HANA instance. + ${HanaDatabasePassword}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.Collections.Hashtable] + # A JSON string containing metadata of the provider instance. + ${Metadata}, + + [Parameter(ParameterSetName='ByKeyVault', Mandatory)] + [Alias('HanaDbPasswordKeyVaultId', 'KeyVaultId')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # Resource ID of the Key Vault that contains the HANA credentials. + ${HanaDatabasePasswordKeyVaultResourceId}, + + [Parameter(ParameterSetName='ByKeyVault', Mandatory)] + [Alias('HanaDbPasswordSecretId', 'SecretId')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # Secret identifier to the Key Vault secret that contains the HANA credentials. + ${HanaDatabasePasswordSecretId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 = @{ + ByString = 'Az.HanaOnAzure.custom\New-AzSapMonitorProviderInstance'; + ByKeyVault = 'Az.HanaOnAzure.custom\New-AzSapMonitorProviderInstance'; + } + if (('ByString', 'ByKeyVault') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/Remove-AzSapMonitor.ps1 b/src/HanaOnAzure/exports/Remove-AzSapMonitor.ps1 new file mode 100644 index 000000000000..92fa88d6ff14 --- /dev/null +++ b/src/HanaOnAzure/exports/Remove-AzSapMonitor.ps1 @@ -0,0 +1,188 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes a SAP monitor with the specified subscription, resource group, and monitor name. +.Description +Deletes a SAP monitor with the specified subscription, resource group, and monitor name. +.Example +PS C:\> Remove-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t02 + +.Example +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Remove-AzSapMonitor -InputObject $sap + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azsapmonitor +#> +function Remove-AzSapMonitor { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.HanaOnAzure.private\Remove-AzSapMonitor_Delete'; + DeleteViaIdentity = 'Az.HanaOnAzure.private\Remove-AzSapMonitor_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/Remove-AzSapMonitorProviderInstance.ps1 b/src/HanaOnAzure/exports/Remove-AzSapMonitorProviderInstance.ps1 new file mode 100644 index 000000000000..209516f5fe58 --- /dev/null +++ b/src/HanaOnAzure/exports/Remove-AzSapMonitorProviderInstance.ps1 @@ -0,0 +1,194 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> Remove-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +.Example +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t01 +PS C:\> Remove-AzSapMonitorProviderInstance -InputObject $sapIns + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azsapmonitorproviderinstance +#> +function Remove-AzSapMonitorProviderInstance { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.HanaOnAzure.private\Remove-AzSapMonitorProviderInstance_Delete'; + DeleteViaIdentity = 'Az.HanaOnAzure.private\Remove-AzSapMonitorProviderInstance_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/Update-AzSapMonitor.ps1 b/src/HanaOnAzure/exports/Update-AzSapMonitor.ps1 new file mode 100644 index 000000000000..3662bdc05656 --- /dev/null +++ b/src/HanaOnAzure/exports/Update-AzSapMonitor.ps1 @@ -0,0 +1,183 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. +.Description +Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. +.Example +PS C:\> Update-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +.Example +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Update-AzSapMonitor -InputObject $sap -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/update-azsapmonitor +#> +function Update-AzSapMonitor { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('SapMonitorName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1]))] + [System.Collections.Hashtable] + # Tags field of the resource. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Update-AzSapMonitor_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.HanaOnAzure.private\Update-AzSapMonitor_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/exports/readme.md b/src/HanaOnAzure/exports/readme.md new file mode 100644 index 000000000000..f588449681dc --- /dev/null +++ b/src/HanaOnAzure/exports/readme.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.HanaOnAzure`. No other cmdlets in this repository are directly exported. What that means is the `Az.HanaOnAzure` module will run [Export-ModuleMember](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.HanaOnAzure.private.dll`) and from the `..\custom\Az.HanaOnAzure.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.HanaOnAzure.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/HanaOnAzure/generate-help.ps1 b/src/HanaOnAzure/generate-help.ps1 new file mode 100644 index 000000000000..4bd0a81aa51f --- /dev/null +++ b/src/HanaOnAzure/generate-help.ps1 @@ -0,0 +1,73 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.HanaOnAzure.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.HanaOnAzure.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/HanaOnAzure/generate-info.json b/src/HanaOnAzure/generate-info.json new file mode 100644 index 000000000000..5a21cbcd505b --- /dev/null +++ b/src/HanaOnAzure/generate-info.json @@ -0,0 +1,8 @@ +{ + "node": "v10.16.0", + "autorest_powershell": "2.1.396", + "autorest": "`-- (empty)", + "autorest_remodeler": "2.1.27", + "autorest_core": "3.0.6282", + "swagger_commit": "3774a2c2f9b847a7695c4f857a5634ed5663d2c7" +} diff --git a/src/HanaOnAzure/generated/Module.cs b/src/HanaOnAzure/generated/Module.cs new file mode 100644 index 000000000000..1378444bf8ca --- /dev/null +++ b/src/HanaOnAzure/generated/Module.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline _pipelineWithProxy; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// Backing field for property. + private static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module _instance; + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module Instance => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module._instance?? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module._instance = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module()); + + /// The Name of this module + public string Name => @"Az.HanaOnAzure"; + + /// 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.HanaOnAzure"; + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_handler.UseProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + } + + /// Creates the module instance. + private Module() + { + /// constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + _webProxy.UseDefaultCredentials = proxyUseDefaultCredentials; + _handler.UseProxy = proxy != null; + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/HanaOnAzure.cs b/src/HanaOnAzure/generated/api/HanaOnAzure.cs new file mode 100644 index 000000000000..cfdcb1ab140f --- /dev/null +++ b/src/HanaOnAzure/generated/api/HanaOnAzure.cs @@ -0,0 +1,5506 @@ +// 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.HanaOnAzure +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Low-level API implementation for the HanaOnAzure service. + /// + public partial class HanaOnAzure + { + + /// Gets a list of SAP HANA management 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.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.HanaOnAzure/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists available operations for the Microsoft.ManagedIdentity provider + /// 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.HanaOnAzure.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 OperationsList1(global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.ManagedIdentity/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList1_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Lists available operations for the Microsoft.ManagedIdentity provider + /// + /// 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.HanaOnAzure.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 OperationsList1ViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.ManagedIdentity/operations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.ManagedIdentity/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.ManagedIdentity/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList1_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 OperationsList1_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 OperationsList1_Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// Gets a list of SAP HANA management 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.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.HanaOnAzure/operations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.HanaOnAzure/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.HanaOnAzure/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.OperationList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// + /// Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Name of the provider instance. + /// Request body representing a provider instance + /// 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.HanaOnAzure.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 ProviderInstancesCreate(string subscriptionId, string resourceGroupName, string sapMonitorName, string providerInstanceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "/providerInstances/" + + global::System.Uri.EscapeDataString(providerInstanceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// Request body representing a provider instance + /// 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.HanaOnAzure.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 ProviderInstancesCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)/providerInstances/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + var providerInstanceName = _match.Groups["providerInstanceName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "/providerInstances/" + + providerInstanceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 ProviderInstancesCreate_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_originalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_originalUri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstance.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Name of the provider instance. + /// Request body representing a provider instance + /// 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 ProviderInstancesCreate_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, string providerInstanceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + await eventListener.AssertNotNull(nameof(providerInstanceName),providerInstanceName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// + /// Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Name of the provider instance. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 ProviderInstancesDelete(string subscriptionId, string resourceGroupName, string sapMonitorName, string providerInstanceName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "/providerInstances/" + + global::System.Uri.EscapeDataString(providerInstanceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// + /// Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 ProviderInstancesDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)/providerInstances/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + var providerInstanceName = _match.Groups["providerInstanceName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "/providerInstances/" + + providerInstanceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 ProviderInstancesDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var _finalUri = _response.GetFirstHeader(@"Location"); + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_finalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Name of the provider instance. + /// 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 ProviderInstancesDelete_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, string providerInstanceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + await eventListener.AssertNotNull(nameof(providerInstanceName),providerInstanceName); + } + } + + /// + /// Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Name of the provider instance. + /// 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.HanaOnAzure.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 ProviderInstancesGet(string subscriptionId, string resourceGroupName, string sapMonitorName, string providerInstanceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "/providerInstances/" + + global::System.Uri.EscapeDataString(providerInstanceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// 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.HanaOnAzure.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 ProviderInstancesGetViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)/providerInstances/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + var providerInstanceName = _match.Groups["providerInstanceName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "/providerInstances/" + + providerInstanceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 ProviderInstancesGet_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstance.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Name of the provider instance. + /// 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 ProviderInstancesGet_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, string providerInstanceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + await eventListener.AssertNotNull(nameof(providerInstanceName),providerInstanceName); + } + } + + /// + /// Gets a list of provider instances in the specified SAP monitor. The operations returns various properties of each provider + /// instances. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// 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.HanaOnAzure.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 ProviderInstancesList(string subscriptionId, string resourceGroupName, string sapMonitorName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "/providerInstances" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Gets a list of provider instances in the specified SAP monitor. The operations returns various properties of each provider + /// instances. + /// + /// + /// 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.HanaOnAzure.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 ProviderInstancesListViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)/providerInstances$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "/providerInstances" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ProviderInstancesList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 ProviderInstancesList_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// 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 ProviderInstancesList_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + } + } + + /// + /// Creates a SAP monitor for the specified subscription, resource group, and resource name. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Request body representing a SAP Monitor + /// 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.HanaOnAzure.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 SapMonitorsCreate(string subscriptionId, string resourceGroupName, string sapMonitorName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Creates a SAP monitor for the specified subscription, resource group, and resource name. + /// + /// + /// Request body representing a SAP Monitor + /// 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.HanaOnAzure.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 SapMonitorsCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsCreate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SapMonitorsCreate_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_originalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_originalUri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitor.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Request body representing a SAP Monitor + /// 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 SapMonitorsCreate_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// + /// Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SapMonitorsDelete(string subscriptionId, string resourceGroupName, string sapMonitorName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// + /// Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + /// + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SapMonitorsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SapMonitorsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var _finalUri = _response.GetFirstHeader(@"Location"); + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_finalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// 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 SapMonitorsDelete_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + } + } + + /// + /// Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// 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.HanaOnAzure.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 SapMonitorsGet(string subscriptionId, string resourceGroupName, string sapMonitorName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + /// + /// + /// 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.HanaOnAzure.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 SapMonitorsGetViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SapMonitorsGet_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitor.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// 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 SapMonitorsGet_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + } + } + + /// + /// Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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.HanaOnAzure.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 SapMonitorsList(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.HanaOnAzure/sapMonitors" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + /// + /// + /// 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.HanaOnAzure.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 SapMonitorsListViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.HanaOnAzure/sapMonitors'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.HanaOnAzure/sapMonitors" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SapMonitorsList_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 SapMonitorsList_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// + /// Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Request body that only contains the new Tags field + /// 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.HanaOnAzure.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 SapMonitorsUpdate(string subscriptionId, string resourceGroupName, string sapMonitorName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + global::System.Uri.EscapeDataString(sapMonitorName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + /// + /// + /// Request body that only contains the new Tags field + /// 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.HanaOnAzure.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 SapMonitorsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2020-02-07-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.HanaOnAzure/sapMonitors/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var sapMonitorName = _match.Groups["sapMonitorName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.HanaOnAzure/sapMonitors/" + + sapMonitorName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SapMonitorsUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SapMonitorsUpdate_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitor.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// Name of the SAP monitor resource. + /// Request body that only contains the new Tags field + /// 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 SapMonitorsUpdate_Validate(string subscriptionId, string resourceGroupName, string sapMonitorName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(sapMonitorName),sapMonitorName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Gets the systemAssignedIdentity available under the specified RP scope. + /// The resource provider scope of the resource. Parent resource being extended by Managed Identities. + /// 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.HanaOnAzure.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 SystemAssignedIdentitiesGetByScope(string scope, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + (scope) + + "/providers/Microsoft.ManagedIdentity/identities/default" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SystemAssignedIdentitiesGetByScope_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets the systemAssignedIdentity available under the specified RP 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.HanaOnAzure.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 SystemAssignedIdentitiesGetByScopeViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/(?[^/]+)/providers/Microsoft.ManagedIdentity/identities/default$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/{scope}/providers/Microsoft.ManagedIdentity/identities/default'"); + } + + // replace URI parameters with values from identity + var scope = _match.Groups["scope"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/" + + scope + + "/providers/Microsoft.ManagedIdentity/identities/default" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SystemAssignedIdentitiesGetByScope_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 SystemAssignedIdentitiesGetByScope_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentity.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 resource provider scope of the resource. Parent resource being extended by Managed Identities. + /// 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 SystemAssignedIdentitiesGetByScope_Validate(string scope, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(scope),scope); + } + } + + /// Create or update an identity in the specified subscription and resource group. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// Parameters to create or update the identity + /// 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.HanaOnAzure.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 UserAssignedIdentitiesCreateOrUpdate(string subscriptionId, string resourceGroupName, string resourceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity 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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + global::System.Uri.EscapeDataString(resourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesCreateOrUpdate_Call(request,onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// Create or update an identity in the specified subscription and resource group. + /// + /// Parameters to create or update the identity + /// 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.HanaOnAzure.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 UserAssignedIdentitiesCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity 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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ManagedIdentity/userAssignedIdentities/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceName = _match.Groups["resourceName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + resourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesCreateOrUpdate_Call(request,onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 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.HanaOnAzure.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 UserAssignedIdentitiesCreateOrUpdate_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// Parameters to create or update the identity + /// 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 UserAssignedIdentitiesCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string resourceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceName),resourceName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the identity. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 UserAssignedIdentitiesDelete(string subscriptionId, string resourceGroupName, string resourceName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + global::System.Uri.EscapeDataString(resourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Deletes the identity. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 UserAssignedIdentitiesDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ManagedIdentity/userAssignedIdentities/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceName = _match.Groups["resourceName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + resourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 UserAssignedIdentitiesDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// 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 UserAssignedIdentitiesDelete_Validate(string subscriptionId, string resourceGroupName, string resourceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceName),resourceName); + } + } + + /// Gets the identity. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// 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.HanaOnAzure.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 UserAssignedIdentitiesGet(string subscriptionId, string resourceGroupName, string resourceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + global::System.Uri.EscapeDataString(resourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets the identity. + /// + /// 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.HanaOnAzure.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 UserAssignedIdentitiesGetViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ManagedIdentity/userAssignedIdentities/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceName = _match.Groups["resourceName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + resourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 UserAssignedIdentitiesGet_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// 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 UserAssignedIdentitiesGet_Validate(string subscriptionId, string resourceGroupName, string resourceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceName),resourceName); + } + } + + /// + /// Lists all the userAssignedIdentities available under the specified ResourceGroup. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// 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.HanaOnAzure.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 UserAssignedIdentitiesListByResourceGroup(string subscriptionId, string resourceGroupName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Lists all the userAssignedIdentities available under the specified ResourceGroup. + /// + /// + /// 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.HanaOnAzure.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 UserAssignedIdentitiesListByResourceGroupViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ManagedIdentity/userAssignedIdentities$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 UserAssignedIdentitiesListByResourceGroup_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentitiesListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// 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 UserAssignedIdentitiesListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + } + } + + /// + /// Lists all the userAssignedIdentities available under the specified subscription. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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.HanaOnAzure.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 UserAssignedIdentitiesListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Lists all the userAssignedIdentities available under the specified subscription. + /// + /// + /// 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.HanaOnAzure.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 UserAssignedIdentitiesListBySubscriptionViaIdentity(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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.ManagedIdentity/userAssignedIdentities$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.ManagedIdentity/userAssignedIdentities'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 UserAssignedIdentitiesListBySubscription_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentitiesListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 UserAssignedIdentitiesListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Update an identity in the specified subscription and resource group. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// Parameters to update the identity + /// 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.HanaOnAzure.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 UserAssignedIdentitiesUpdate(string subscriptionId, string resourceGroupName, string resourceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + global::System.Uri.EscapeDataString(resourceName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Update an identity in the specified subscription and resource group. + /// + /// Parameters to update the identity + /// 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.HanaOnAzure.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 UserAssignedIdentitiesUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2018-11-30"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.ManagedIdentity/userAssignedIdentities/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var resourceName = _match.Groups["resourceName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.ManagedIdentity/userAssignedIdentities/" + + resourceName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.UserAssignedIdentitiesUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 UserAssignedIdentitiesUpdate_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.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Name of the resource group. + /// The name of the identity resource. + /// Parameters to update the identity + /// 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 UserAssignedIdentitiesUpdate_Validate(string subscriptionId, string resourceGroupName, string resourceName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(resourceName),resourceName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Checks that the vault name is valid and is not already in use. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// The name of the vault. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsCheckNameAvailability(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.KeyVault/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsCheckNameAvailability_Call(request,onOk,eventListener,sender); + } + } + + /// Checks that the vault name is valid and is not already in use. + /// + /// The name of the vault. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsCheckNameAvailabilityViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.KeyVault/checkNameAvailability$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/checkNameAvailability'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.KeyVault/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsCheckNameAvailability_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsCheckNameAvailability_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.CheckNameAvailabilityResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// The name of the vault. + /// 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 VaultsCheckNameAvailability_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Create or update a key vault in the specified subscription. + /// The name of the Resource Group to which the server belongs. + /// Name of the vault + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Parameters to create or update the vault + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsCreateOrUpdate(string resourceGroupName, string vaultName, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.KeyVault/vaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsCreateOrUpdate_Call(request,onOk,onCreated,eventListener,sender); + } + } + + /// Create or update a key vault in the specified subscription. + /// + /// Parameters to create or update the vault + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.KeyVault/vaults/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.KeyVault/vaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsCreateOrUpdate_Call(request,onOk,onCreated,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsCreateOrUpdate_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, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the Resource Group to which the server belongs. + /// Name of the vault + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Parameters to create or update the vault + /// 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 VaultsCreateOrUpdate_Validate(string resourceGroupName, string vaultName, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName),vaultName,@"^[a-zA-Z0-9-]{3,24}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the specified Azure key vault. + /// The name of the Resource Group to which the vault belongs. + /// The name of the vault to delete + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsDelete(string resourceGroupName, string vaultName, string subscriptionId, global::System.Func onOk, global::System.Func onNoContent, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.KeyVault/vaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsDelete_Call(request,onOk,onNoContent,eventListener,sender); + } + } + + /// Deletes the specified Azure key vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.KeyVault/vaults/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.KeyVault/vaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsDelete_Call(request,onOk,onNoContent,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the Resource Group to which the vault belongs. + /// The name of the vault to delete + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsDelete_Validate(string resourceGroupName, string vaultName, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Gets the specified Azure key vault. + /// The name of the Resource Group to which the vault belongs. + /// The name of the vault. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsGet(string resourceGroupName, string vaultName, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.KeyVault/vaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsGet_Call(request,onOk,eventListener,sender); + } + } + + /// Gets the deleted Azure key vault. + /// The name of the vault. + /// The location of the deleted vault. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsGetDeleted(string vaultName, string location, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.KeyVault/locations/" + + global::System.Uri.EscapeDataString(location) + + "/deletedVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsGetDeleted_Call(request,onOk,eventListener,sender); + } + } + + /// Gets the deleted Azure key vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsGetDeletedViaIdentity(global::System.String viaIdentity, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.KeyVault/locations/(?[^/]+)/deletedVaults/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var vaultName = _match.Groups["vaultName"].Value; + var location = _match.Groups["location"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.KeyVault/locations/" + + location + + "/deletedVaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsGetDeleted_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsGetDeleted_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVault.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the vault. + /// The location of the deleted vault. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsGetDeleted_Validate(string vaultName, string location, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Gets the specified Azure key vault. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsGetViaIdentity(global::System.String viaIdentity, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.KeyVault/vaults/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.KeyVault/vaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsGet_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsGet_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the Resource Group to which the vault belongs. + /// The name of the vault. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsGet_Validate(string resourceGroupName, string vaultName, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// + /// The List operation gets information about the vaults associated with the subscription. + /// + /// Maximum number of results to return. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsList(int? Top, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var Filter = @"resourceType eq 'Microsoft.KeyVault/vaults'"; + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resources" + + "?" + + "$filter=" + global::System.Uri.EscapeDataString(Filter) + + "&" + + (null == Top ? global::System.String.Empty : "$top=" + global::System.Uri.EscapeDataString(Top.ToString())) + + "&" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsList_Call(request,onOk,eventListener,sender); + } + } + + /// + /// The List operation gets information about the vaults associated with the subscription and within the specified resource + /// group. + /// + /// The name of the Resource Group to which the vault belongs. + /// Maximum number of results to return. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListByResourceGroup(string resourceGroupName, int? Top, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.KeyVault/vaults" + + "?" + + (null == Top ? global::System.String.Empty : "$top=" + global::System.Uri.EscapeDataString(Top.ToString())) + + "&" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsListByResourceGroup_Call(request,onOk,eventListener,sender); + } + } + + /// + /// The List operation gets information about the vaults associated with the subscription and within the specified resource + /// group. + /// + /// + /// Maximum number of results to return. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListByResourceGroupViaIdentity(global::System.String viaIdentity, int? Top, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.KeyVault/vaults$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults'"); + } + + // replace URI parameters with values from identity + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.KeyVault/vaults" + + "?" + + (null == Top ? global::System.String.Empty : "$top=" + global::System.Uri.EscapeDataString(Top.ToString())) + + "&" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsListByResourceGroup_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListByResourceGroup_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the Resource Group to which the vault belongs. + /// Maximum number of results to return. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsListByResourceGroup_Validate(string resourceGroupName, int? Top, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// + /// The List operation gets information about the vaults associated with the subscription. + /// + /// Maximum number of results to return. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListBySubscription(int? Top, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.KeyVault/vaults" + + "?" + + (null == Top ? global::System.String.Empty : "$top=" + global::System.Uri.EscapeDataString(Top.ToString())) + + "&" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsListBySubscription_Call(request,onOk,eventListener,sender); + } + } + + /// + /// The List operation gets information about the vaults associated with the subscription. + /// + /// + /// Maximum number of results to return. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListBySubscriptionViaIdentity(global::System.String viaIdentity, int? Top, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.KeyVault/vaults$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/vaults'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.KeyVault/vaults" + + "?" + + (null == Top ? global::System.String.Empty : "$top=" + global::System.Uri.EscapeDataString(Top.ToString())) + + "&" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsListBySubscription_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListBySubscription_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Maximum number of results to return. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsListBySubscription_Validate(int? Top, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Gets information about the deleted vaults in a subscription. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListDeleted(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.KeyVault/deletedVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsListDeleted_Call(request,onOk,eventListener,sender); + } + } + + /// Gets information about the deleted vaults in a subscription. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListDeletedViaIdentity(global::System.String viaIdentity, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.KeyVault/deletedVaults$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedVaults'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.KeyVault/deletedVaults" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsListDeleted_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListDeleted_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsListDeleted_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// + /// The List operation gets information about the vaults associated with the subscription. + /// + /// + /// Maximum number of results to return. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsListViaIdentity(global::System.String viaIdentity, int? Top, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var Filter = @"resourceType eq 'Microsoft.KeyVault/vaults'"; + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resources$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resources'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resources" + + "?" + + "$filter=" + global::System.Uri.EscapeDataString(Filter) + + "&" + + (null == Top ? global::System.String.Empty : "$top=" + global::System.Uri.EscapeDataString(Top.ToString())) + + "&" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsList_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsList_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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. + /// + /// Maximum number of results to return. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsList_Validate(int? Top, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// + /// Permanently deletes the specified vault. aka Purges the deleted Azure key vault. + /// + /// The name of the soft-deleted vault. + /// The location of the soft-deleted vault. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsPurgeDeleted(string vaultName, string location, string subscriptionId, global::System.Func onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.KeyVault/locations/" + + global::System.Uri.EscapeDataString(location) + + "/deletedVaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/purge" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsPurgeDeleted_Call(request,onOk,eventListener,sender); + } + } + + /// + /// Permanently deletes the specified vault. aka Purges the deleted Azure key vault. + /// + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsPurgeDeletedViaIdentity(global::System.String viaIdentity, global::System.Func onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.KeyVault/locations/(?[^/]+)/deletedVaults/(?[^/]+)/purge$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}/purge'"); + } + + // replace URI parameters with values from identity + var vaultName = _match.Groups["vaultName"].Value; + var location = _match.Groups["location"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.KeyVault/locations/" + + location + + "/deletedVaults/" + + vaultName + + "/purge" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsPurgeDeleted_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsPurgeDeleted_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var _finalUri = _response.GetFirstHeader(@"Location"); + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_finalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the soft-deleted vault. + /// The location of the soft-deleted vault. + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// 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 VaultsPurgeDeleted_Validate(string vaultName, string location, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertNotNull(nameof(location),location); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Update a key vault in the specified subscription. + /// The name of the Resource Group to which the server belongs. + /// Name of the vault + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Parameters to patch the vault + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsUpdate(string resourceGroupName, string vaultName, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.KeyVault/vaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsUpdate_Call(request,onOk,onCreated,eventListener,sender); + } + } + + /// Update access policies in a key vault in the specified subscription. + /// The name of the Resource Group to which the vault belongs. + /// Name of the vault + /// Name of the operation + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Access policy to merge into the vault + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsUpdateAccessPolicy(string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind operationKind, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.KeyVault/vaults/" + + global::System.Uri.EscapeDataString(vaultName) + + "/accessPolicies/" + + global::System.Uri.EscapeDataString(operationKind) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsUpdateAccessPolicy_Call(request,onOk,onCreated,eventListener,sender); + } + } + + /// Update access policies in a key vault in the specified subscription. + /// + /// Access policy to merge into the vault + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsUpdateAccessPolicyViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.KeyVault/vaults/(?[^/]+)/accessPolicies/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/accessPolicies/{operationKind}'"); + } + + // replace URI parameters with values from identity + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var operationKind = _match.Groups["operationKind"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.KeyVault/vaults/" + + vaultName + + "/accessPolicies/" + + operationKind + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsUpdateAccessPolicy_Call(request,onOk,onCreated,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsUpdateAccessPolicy_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, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyParameters.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyParameters.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the Resource Group to which the vault belongs. + /// Name of the vault + /// Name of the operation + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Access policy to merge into the vault + /// 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 VaultsUpdateAccessPolicy_Validate(string resourceGroupName, string vaultName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind operationKind, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName),vaultName,@"^[a-zA-Z0-9-]{3,24}$"); + await eventListener.AssertNotNull(nameof(operationKind),operationKind); + await eventListener.AssertEnum(nameof(operationKind),operationKind,@"add", @"replace", @"remove"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Update a key vault in the specified subscription. + /// + /// Parameters to patch the vault + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onCreated, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + var apiVersion = @"2016-10-01"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/Microsoft.KeyVault/vaults/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'"); + } + + // replace URI parameters with values from identity + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var vaultName = _match.Groups["vaultName"].Value; + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.KeyVault/vaults/" + + vaultName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.VaultsUpdate_Call(request,onOk,onCreated,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 201 (Created). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 VaultsUpdate_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, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault.FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 name of the Resource Group to which the server belongs. + /// Name of the vault + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID + /// forms part of the URI for every service call. + /// Parameters to patch the vault + /// 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 VaultsUpdate_Validate(string resourceGroupName, string vaultName, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters body, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(vaultName),vaultName); + await eventListener.AssertRegEx(nameof(vaultName),vaultName,@"^[a-zA-Z0-9-]{3,24}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.PowerShell.cs new file mode 100644 index 000000000000..e10a965e58cf --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// The resource model definition for a ARM proxy resource. It will have everything other than required location and tags + /// + [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); + + /// + /// 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.HanaOnAzure.Models.Api10.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.HanaOnAzure.Models.Api10.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.HanaOnAzure.Models.Api10.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)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 ProxyResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The resource model definition for a ARM proxy resource. It will have everything other than required location and tags + [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] + public partial interface IProxyResource + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.TypeConverter.cs new file mode 100644 index 000000000000..c074ea51b078 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.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/HanaOnAzure/generated/api/Models/Api10/ProxyResource.cs b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.cs new file mode 100644 index 000000000000..be43d617d7b5 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// The resource model definition for a ARM proxy resource. It will have everything other than required location and tags + /// + public partial class ProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource(); + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.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 < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for a ARM proxy resource. It will have everything other than required location and tags + public partial interface IProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource + { + + } + /// The resource model definition for a ARM proxy resource. It will have everything other than required location and tags + internal partial interface IProxyResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.json.cs b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.json.cs new file mode 100644 index 000000000000..d944904056df --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/ProxyResource.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// The resource model definition for a ARM proxy resource. It will have everything other than required location and tags + /// + 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api10/Resource.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api10/Resource.PowerShell.cs new file mode 100644 index 000000000000..803ef3d9cf8a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/Resource.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Key Vault resource + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.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.HanaOnAzure.Models.Api10.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.HanaOnAzure.Models.Api10.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)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 Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Key Vault resource + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/Resource.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api10/Resource.TypeConverter.cs new file mode 100644 index 000000000000..9e2600731d88 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/Resource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.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/HanaOnAzure/generated/api/Models/Api10/Resource.cs b/src/HanaOnAzure/generated/api/Models/Api10/Resource.cs new file mode 100644 index 000000000000..ce80c39828cc --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/Resource.cs @@ -0,0 +1,89 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Key Vault resource + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal + { + + /// Backing field for property. + private string _id; + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _type; + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// Key Vault resource + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The Azure Resource Manager resource ID for the key vault.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the key vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource type of the key vault.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Key Vault resource + internal partial interface IResourceInternal + + { + /// The Azure Resource Manager resource ID for the key vault. + string Id { get; set; } + /// The name of the key vault. + string Name { get; set; } + /// The resource type of the key vault. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/Resource.json.cs b/src/HanaOnAzure/generated/api/Models/Api10/Resource.json.cs new file mode 100644 index 000000000000..2aa8fcd068cd --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/Resource.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Key Vault resource + public partial class Resource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api10/TrackedResource.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.PowerShell.cs new file mode 100644 index 000000000000..cafbedada330 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The resource model definition for a ARM tracked top level resource + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial class TrackedResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResource(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.HanaOnAzure.Models.Api10.ITrackedResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResource(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.HanaOnAzure.Models.Api10.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TrackedResource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)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 TrackedResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + } + /// The resource model definition for a ARM tracked top level resource + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial interface ITrackedResource + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.TypeConverter.cs new file mode 100644 index 000000000000..9967e909531e --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResource.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/HanaOnAzure/generated/api/Models/Api10/TrackedResource.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.cs new file mode 100644 index 000000000000..e930652c43b9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The resource model definition for a ARM tracked top level resource + public partial class TrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource(); + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTags()); set => this._tag = value; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; } + + /// Creates an new instance. + public TrackedResource() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for a ARM tracked top level resource + public partial interface ITrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get; set; } + + } + /// The resource model definition for a ARM tracked top level resource + internal partial interface ITrackedResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.json.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.json.cs new file mode 100644 index 000000000000..22412288b51c --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResource.json.cs @@ -0,0 +1,105 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The resource model definition for a ARM tracked top level resource + public partial class TrackedResource + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new TrackedResource(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource(json); + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.PowerShell.cs new file mode 100644 index 000000000000..174b8e70b86b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial class TrackedResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new TrackedResourceTags(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.HanaOnAzure.Models.Api10.ITrackedResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new TrackedResourceTags(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.HanaOnAzure.Models.Api10.ITrackedResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal TrackedResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTagsTypeConverter))] + public partial interface ITrackedResourceTags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.TypeConverter.cs new file mode 100644 index 000000000000..74bd375d0763 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TrackedResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return TrackedResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return TrackedResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return TrackedResourceTags.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/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.cs new file mode 100644 index 000000000000..340062cdcb14 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTagsInternal + { + + /// Creates an new instance. + public TrackedResourceTags() + { + + } + } + /// Resource tags. + public partial interface ITrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITrackedResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.dictionary.cs new file mode 100644 index 000000000000..db636c4e16b9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class TrackedResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.json.cs b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.json.cs new file mode 100644 index 000000000000..883045fa0cf4 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api10/TrackedResourceTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource tags. + public partial class TrackedResourceTags + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new TrackedResourceTags(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal TrackedResourceTags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.PowerShell.cs new file mode 100644 index 000000000000..7f2d86b30b33 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.PowerShell.cs @@ -0,0 +1,149 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// An identity that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's + /// tenant ID. + /// + [System.ComponentModel.TypeConverter(typeof(AccessPolicyEntryTypeConverter))] + public partial class AccessPolicyEntry + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal AccessPolicyEntry(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).Permission = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions) content.GetValueForProperty("Permission",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).Permission, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.PermissionsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ApplicationId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ObjectId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionCertificate = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[]) content.GetValueForProperty("PermissionCertificate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionCertificate, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionKey = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[]) content.GetValueForProperty("PermissionKey",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionKey, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionSecret = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[]) content.GetValueForProperty("PermissionSecret",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionSecret, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionStorage = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[]) content.GetValueForProperty("PermissionStorage",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionStorage, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions.CreateFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AccessPolicyEntry(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).Permission = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions) content.GetValueForProperty("Permission",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).Permission, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.PermissionsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ApplicationId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ObjectId = (string) content.GetValueForProperty("ObjectId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).ObjectId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionCertificate = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[]) content.GetValueForProperty("PermissionCertificate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionCertificate, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionKey = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[]) content.GetValueForProperty("PermissionKey",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionKey, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionSecret = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[]) content.GetValueForProperty("PermissionSecret",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionSecret, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionStorage = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[]) content.GetValueForProperty("PermissionStorage",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal)this).PermissionStorage, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions.CreateFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AccessPolicyEntry(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.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AccessPolicyEntry(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.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// An identity that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's + /// tenant ID. + [System.ComponentModel.TypeConverter(typeof(AccessPolicyEntryTypeConverter))] + public partial interface IAccessPolicyEntry + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.TypeConverter.cs new file mode 100644 index 000000000000..98d25ea75a37 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AccessPolicyEntryTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AccessPolicyEntry.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AccessPolicyEntry.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AccessPolicyEntry.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/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.cs new file mode 100644 index 000000000000..cccbfe5292ab --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.cs @@ -0,0 +1,168 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// An identity that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's + /// tenant ID. + /// + public partial class AccessPolicyEntry : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal + { + + /// Backing field for property. + private string _applicationId; + + /// Application ID of the client making request on behalf of a principal + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ApplicationId { get => this._applicationId; set => this._applicationId = value; } + + /// Internal Acessors for Permission + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntryInternal.Permission { get => (this._permission = this._permission ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Permissions()); set { {_permission = value;} } } + + /// Backing field for property. + private string _objectId; + + /// + /// The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault. The object + /// ID must be unique for the list of access policies. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ObjectId { get => this._objectId; set => this._objectId = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions _permission; + + /// Permissions the identity has for keys, secrets and certificates. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions Permission { get => (this._permission = this._permission ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Permissions()); set => this._permission = value; } + + /// Permissions to certificates + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[] PermissionCertificate { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Certificate; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Certificate = value; } + + /// Permissions to keys + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[] PermissionKey { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Key; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Key = value; } + + /// Permissions to secrets + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[] PermissionSecret { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Secret; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Secret = value; } + + /// Permissions to storage accounts + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[] PermissionStorage { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Storage; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)Permission).Storage = value; } + + /// Backing field for property. + private string _tenantId; + + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; set => this._tenantId = value; } + + /// Creates an new instance. + public AccessPolicyEntry() + { + + } + } + /// An identity that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's + /// tenant ID. + public partial interface IAccessPolicyEntry : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// Application ID of the client making request on behalf of a principal + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @" Application ID of the client making request on behalf of a principal", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ApplicationId { get; set; } + /// + /// The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault. The object + /// ID must be unique for the list of access policies. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault. The object ID must be unique for the list of access policies.", + SerializedName = @"objectId", + PossibleTypes = new [] { typeof(string) })] + string ObjectId { get; set; } + /// Permissions to certificates + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to certificates", + SerializedName = @"certificates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[] PermissionCertificate { get; set; } + /// Permissions to keys + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to keys", + SerializedName = @"keys", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[] PermissionKey { get; set; } + /// Permissions to secrets + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to secrets", + SerializedName = @"secrets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[] PermissionSecret { get; set; } + /// Permissions to storage accounts + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to storage accounts", + SerializedName = @"storage", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[] PermissionStorage { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + + } + /// An identity that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's + /// tenant ID. + internal partial interface IAccessPolicyEntryInternal + + { + /// Application ID of the client making request on behalf of a principal + string ApplicationId { get; set; } + /// + /// The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault. The object + /// ID must be unique for the list of access policies. + /// + string ObjectId { get; set; } + /// Permissions the identity has for keys, secrets and certificates. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions Permission { get; set; } + /// Permissions to certificates + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[] PermissionCertificate { get; set; } + /// Permissions to keys + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[] PermissionKey { get; set; } + /// Permissions to secrets + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[] PermissionSecret { get; set; } + /// Permissions to storage accounts + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[] PermissionStorage { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.json.cs new file mode 100644 index 000000000000..b6df4dd9659d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/AccessPolicyEntry.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// An identity that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's + /// tenant ID. + /// + public partial class AccessPolicyEntry + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal AccessPolicyEntry(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_permission = If( json?.PropertyT("permissions"), out var __jsonPermissions) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Permissions.FromJson(__jsonPermissions) : Permission;} + {_applicationId = If( json?.PropertyT("applicationId"), out var __jsonApplicationId) ? (string)__jsonApplicationId : (string)ApplicationId;} + {_objectId = If( json?.PropertyT("objectId"), out var __jsonObjectId) ? (string)__jsonObjectId : (string)ObjectId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)TenantId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new AccessPolicyEntry(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._permission ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._permission.ToJson(null,serializationMode) : null, "permissions" ,container.Add ); + AddIf( null != (((object)this._applicationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._applicationId.ToString()) : null, "applicationId" ,container.Add ); + AddIf( null != (((object)this._objectId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._objectId.ToString()) : null, "objectId" ,container.Add ); + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.PowerShell.cs new file mode 100644 index 000000000000..5d937bf677d5 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The CheckNameAvailability operation response. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityResultTypeConverter))] + public partial class CheckNameAvailabilityResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CheckNameAvailabilityResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Reason = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason?) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Reason, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason.CreateFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CheckNameAvailabilityResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Reason = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason?) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal)this).Reason, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason.CreateFrom); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CheckNameAvailabilityResult(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.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CheckNameAvailabilityResult(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.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The CheckNameAvailability operation response. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityResultTypeConverter))] + public partial interface ICheckNameAvailabilityResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.TypeConverter.cs new file mode 100644 index 000000000000..0d2e23a6d3de --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CheckNameAvailabilityResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CheckNameAvailabilityResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CheckNameAvailabilityResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CheckNameAvailabilityResult.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/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.cs new file mode 100644 index 000000000000..06fb75eadd42 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.cs @@ -0,0 +1,104 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The CheckNameAvailability operation response. + public partial class CheckNameAvailabilityResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal + { + + /// Backing field for property. + private string _message; + + /// An error message explaining the Reason value in more detail. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for NameAvailable + bool? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal.NameAvailable { get => this._nameAvailable; set { {_nameAvailable = value;} } } + + /// Internal Acessors for Reason + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResultInternal.Reason { get => this._reason; set { {_reason = value;} } } + + /// Backing field for property. + private bool? _nameAvailable; + + /// + /// A boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, + /// the name has already been taken or is invalid and cannot be used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? NameAvailable { get => this._nameAvailable; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason? _reason; + + /// + /// The reason that a vault name could not be used. The Reason element is only returned if NameAvailable is false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason? Reason { get => this._reason; } + + /// Creates an new instance. + public CheckNameAvailabilityResult() + { + + } + } + /// The CheckNameAvailability operation response. + public partial interface ICheckNameAvailabilityResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// An error message explaining the Reason value in more detail. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"An error message explaining the Reason value in more detail.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// + /// A boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, + /// the name has already been taken or is invalid and cannot be used. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"A boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, the name has already been taken or is invalid and cannot be used.", + SerializedName = @"nameAvailable", + PossibleTypes = new [] { typeof(bool) })] + bool? NameAvailable { get; } + /// + /// The reason that a vault name could not be used. The Reason element is only returned if NameAvailable is false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The reason that a vault name could not be used. The Reason element is only returned if NameAvailable is false.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason? Reason { get; } + + } + /// The CheckNameAvailability operation response. + internal partial interface ICheckNameAvailabilityResultInternal + + { + /// An error message explaining the Reason value in more detail. + string Message { get; set; } + /// + /// A boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, + /// the name has already been taken or is invalid and cannot be used. + /// + bool? NameAvailable { get; set; } + /// + /// The reason that a vault name could not be used. The Reason element is only returned if NameAvailable is false. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason? Reason { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.json.cs new file mode 100644 index 000000000000..56422c67b5bf --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/CheckNameAvailabilityResult.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The CheckNameAvailability operation response. + public partial class CheckNameAvailabilityResult + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal CheckNameAvailabilityResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;} + {_nameAvailable = If( json?.PropertyT("nameAvailable"), out var __jsonNameAvailable) ? (bool?)__jsonNameAvailable : NameAvailable;} + {_reason = If( json?.PropertyT("reason"), out var __jsonReason) ? (string)__jsonReason : (string)Reason;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ICheckNameAvailabilityResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new CheckNameAvailabilityResult(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._nameAvailable ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._nameAvailable) : null, "nameAvailable" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._reason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._reason.ToString()) : null, "reason" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.PowerShell.cs new file mode 100644 index 000000000000..a7eb80c4663a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.PowerShell.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Deleted vault information with extended details. + [System.ComponentModel.TypeConverter(typeof(DeletedVaultTypeConverter))] + public partial class DeletedVault + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DeletedVault(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).DeletionDate = (global::System.DateTime?) content.GetValueForProperty("DeletionDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).DeletionDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).ScheduledPurgeDate = (global::System.DateTime?) content.GetValueForProperty("ScheduledPurgeDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).ScheduledPurgeDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).VaultId = (string) content.GetValueForProperty("VaultId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).VaultId, 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 DeletedVault(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).DeletionDate = (global::System.DateTime?) content.GetValueForProperty("DeletionDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).DeletionDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).ScheduledPurgeDate = (global::System.DateTime?) content.GetValueForProperty("ScheduledPurgeDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).ScheduledPurgeDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).VaultId = (string) content.GetValueForProperty("VaultId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal)this).VaultId, 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.HanaOnAzure.Models.Api20161001.IDeletedVault DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DeletedVault(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.HanaOnAzure.Models.Api20161001.IDeletedVault DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DeletedVault(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.HanaOnAzure.Models.Api20161001.IDeletedVault FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Deleted vault information with extended details. + [System.ComponentModel.TypeConverter(typeof(DeletedVaultTypeConverter))] + public partial interface IDeletedVault + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.TypeConverter.cs new file mode 100644 index 000000000000..027cd7a6448a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DeletedVaultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DeletedVault.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DeletedVault.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DeletedVault.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/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.cs new file mode 100644 index 000000000000..e403a85fcd64 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.cs @@ -0,0 +1,186 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Deleted vault information with extended details. + public partial class DeletedVault : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal + { + + /// The deleted date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public global::System.DateTime? DeletionDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).DeletionDate; } + + /// Backing field for property. + private string _id; + + /// The resource ID for the deleted key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// The location of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).Location; } + + /// Internal Acessors for DeletionDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.DeletionDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).DeletionDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).DeletionDate = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Location + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).Location = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultProperties()); set { {_property = value;} } } + + /// Internal Acessors for ScheduledPurgeDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.ScheduledPurgeDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).ScheduledPurgeDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).ScheduledPurgeDate = value; } + + /// Internal Acessors for Tag + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).Tag = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.Type { get => this._type; set { {_type = value;} } } + + /// Internal Acessors for VaultId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultInternal.VaultId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).VaultId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).VaultId = value; } + + /// Backing field for property. + private string _name; + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties _property; + + /// Properties of the vault + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultProperties()); set => this._property = value; } + + /// The scheduled purged date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public global::System.DateTime? ScheduledPurgeDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).ScheduledPurgeDate; } + + /// Tags of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).Tag; } + + /// Backing field for property. + private string _type; + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// The resource id of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string VaultId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)Property).VaultId; } + + /// Creates an new instance. + public DeletedVault() + { + + } + } + /// Deleted vault information with extended details. + public partial interface IDeletedVault : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The deleted date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The deleted date.", + SerializedName = @"deletionDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? DeletionDate { get; } + /// The resource ID for the deleted key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource ID for the deleted key vault.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// The location of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The location of the original vault.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; } + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the key vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The scheduled purged date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The scheduled purged date.", + SerializedName = @"scheduledPurgeDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? ScheduledPurgeDate { get; } + /// Tags of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Tags of the original vault.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Tag { get; } + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource type of the key vault.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + /// The resource id of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource id of the original vault.", + SerializedName = @"vaultId", + PossibleTypes = new [] { typeof(string) })] + string VaultId { get; } + + } + /// Deleted vault information with extended details. + internal partial interface IDeletedVaultInternal + + { + /// The deleted date. + global::System.DateTime? DeletionDate { get; set; } + /// The resource ID for the deleted key vault. + string Id { get; set; } + /// The location of the original vault. + string Location { get; set; } + /// The name of the key vault. + string Name { get; set; } + /// Properties of the vault + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties Property { get; set; } + /// The scheduled purged date. + global::System.DateTime? ScheduledPurgeDate { get; set; } + /// Tags of the original vault. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Tag { get; set; } + /// The resource type of the key vault. + string Type { get; set; } + /// The resource id of the original vault. + string VaultId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.json.cs new file mode 100644 index 000000000000..741831cfb1e8 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVault.json.cs @@ -0,0 +1,116 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Deleted vault information with extended details. + public partial class DeletedVault + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal DeletedVault(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultProperties.FromJson(__jsonProperties) : Property;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new DeletedVault(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.PowerShell.cs new file mode 100644 index 000000000000..59a8478f1484 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// List of vaults + [System.ComponentModel.TypeConverter(typeof(DeletedVaultListResultTypeConverter))] + public partial class DeletedVaultListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DeletedVaultListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal DeletedVaultListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DeletedVaultListResult(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.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DeletedVaultListResult(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.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// List of vaults + [System.ComponentModel.TypeConverter(typeof(DeletedVaultListResultTypeConverter))] + public partial interface IDeletedVaultListResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.TypeConverter.cs new file mode 100644 index 000000000000..4171ba238dd9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DeletedVaultListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DeletedVaultListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DeletedVaultListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DeletedVaultListResult.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/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.cs new file mode 100644 index 000000000000..99be4e81239d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of vaults + public partial class DeletedVaultListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to get the next set of deleted vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault[] _value; + + /// The list of deleted vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public DeletedVaultListResult() + { + + } + } + /// List of vaults + public partial interface IDeletedVaultListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The URL to get the next set of deleted vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to get the next set of deleted vaults.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of deleted vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of deleted vaults.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault[] Value { get; set; } + + } + /// List of vaults + internal partial interface IDeletedVaultListResultInternal + + { + /// The URL to get the next set of deleted vaults. + string NextLink { get; set; } + /// The list of deleted vaults. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.json.cs new file mode 100644 index 000000000000..d47720762ff5 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of vaults + public partial class DeletedVaultListResult + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal DeletedVaultListResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVault) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVault.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new DeletedVaultListResult(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.PowerShell.cs new file mode 100644 index 000000000000..95361d29eee3 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Properties of the deleted vault. + [System.ComponentModel.TypeConverter(typeof(DeletedVaultPropertiesTypeConverter))] + public partial class DeletedVaultProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DeletedVaultProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).DeletionDate = (global::System.DateTime?) content.GetValueForProperty("DeletionDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).DeletionDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).ScheduledPurgeDate = (global::System.DateTime?) content.GetValueForProperty("ScheduledPurgeDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).ScheduledPurgeDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).VaultId = (string) content.GetValueForProperty("VaultId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).VaultId, 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 DeletedVaultProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).DeletionDate = (global::System.DateTime?) content.GetValueForProperty("DeletionDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).DeletionDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).ScheduledPurgeDate = (global::System.DateTime?) content.GetValueForProperty("ScheduledPurgeDate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).ScheduledPurgeDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).VaultId = (string) content.GetValueForProperty("VaultId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal)this).VaultId, 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.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DeletedVaultProperties(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.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DeletedVaultProperties(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.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Properties of the deleted vault. + [System.ComponentModel.TypeConverter(typeof(DeletedVaultPropertiesTypeConverter))] + public partial interface IDeletedVaultProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.TypeConverter.cs new file mode 100644 index 000000000000..da091c299655 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DeletedVaultPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DeletedVaultProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DeletedVaultProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DeletedVaultProperties.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/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.cs new file mode 100644 index 000000000000..0c507d0a0a71 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.cs @@ -0,0 +1,129 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the deleted vault. + public partial class DeletedVaultProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal + { + + /// Backing field for property. + private global::System.DateTime? _deletionDate; + + /// The deleted date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public global::System.DateTime? DeletionDate { get => this._deletionDate; } + + /// Backing field for property. + private string _location; + + /// The location of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; } + + /// Internal Acessors for DeletionDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal.DeletionDate { get => this._deletionDate; set { {_deletionDate = value;} } } + + /// Internal Acessors for Location + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal.Location { get => this._location; set { {_location = value;} } } + + /// Internal Acessors for ScheduledPurgeDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal.ScheduledPurgeDate { get => this._scheduledPurgeDate; set { {_scheduledPurgeDate = value;} } } + + /// Internal Acessors for Tag + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal.Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTags()); set { {_tag = value;} } } + + /// Internal Acessors for VaultId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesInternal.VaultId { get => this._vaultId; set { {_vaultId = value;} } } + + /// Backing field for property. + private global::System.DateTime? _scheduledPurgeDate; + + /// The scheduled purged date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public global::System.DateTime? ScheduledPurgeDate { get => this._scheduledPurgeDate; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags _tag; + + /// Tags of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTags()); } + + /// Backing field for property. + private string _vaultId; + + /// The resource id of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string VaultId { get => this._vaultId; } + + /// Creates an new instance. + public DeletedVaultProperties() + { + + } + } + /// Properties of the deleted vault. + public partial interface IDeletedVaultProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The deleted date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The deleted date.", + SerializedName = @"deletionDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? DeletionDate { get; } + /// The location of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The location of the original vault.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; } + /// The scheduled purged date. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The scheduled purged date.", + SerializedName = @"scheduledPurgeDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? ScheduledPurgeDate { get; } + /// Tags of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Tags of the original vault.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Tag { get; } + /// The resource id of the original vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource id of the original vault.", + SerializedName = @"vaultId", + PossibleTypes = new [] { typeof(string) })] + string VaultId { get; } + + } + /// Properties of the deleted vault. + internal partial interface IDeletedVaultPropertiesInternal + + { + /// The deleted date. + global::System.DateTime? DeletionDate { get; set; } + /// The location of the original vault. + string Location { get; set; } + /// The scheduled purged date. + global::System.DateTime? ScheduledPurgeDate { get; set; } + /// Tags of the original vault. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags Tag { get; set; } + /// The resource id of the original vault. + string VaultId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.json.cs new file mode 100644 index 000000000000..5b77b55b5fd1 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultProperties.json.cs @@ -0,0 +1,124 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the deleted vault. + public partial class DeletedVaultProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal DeletedVaultProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_deletionDate = If( json?.PropertyT("deletionDate"), out var __jsonDeletionDate) ? global::System.DateTime.TryParse((string)__jsonDeletionDate, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonDeletionDateValue) ? __jsonDeletionDateValue : DeletionDate : DeletionDate;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_scheduledPurgeDate = If( json?.PropertyT("scheduledPurgeDate"), out var __jsonScheduledPurgeDate) ? global::System.DateTime.TryParse((string)__jsonScheduledPurgeDate, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonScheduledPurgeDateValue) ? __jsonScheduledPurgeDateValue : ScheduledPurgeDate : ScheduledPurgeDate;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTags.FromJson(__jsonTags) : Tag;} + {_vaultId = If( json?.PropertyT("vaultId"), out var __jsonVaultId) ? (string)__jsonVaultId : (string)VaultId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new DeletedVaultProperties(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._deletionDate ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._deletionDate?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "deletionDate" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._scheduledPurgeDate ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._scheduledPurgeDate?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "scheduledPurgeDate" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._vaultId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._vaultId.ToString()) : null, "vaultId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.PowerShell.cs new file mode 100644 index 000000000000..9b4a5014b53a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Tags of the original vault. + [System.ComponentModel.TypeConverter(typeof(DeletedVaultPropertiesTagsTypeConverter))] + public partial class DeletedVaultPropertiesTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal DeletedVaultPropertiesTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal DeletedVaultPropertiesTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new DeletedVaultPropertiesTags(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.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new DeletedVaultPropertiesTags(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.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Tags of the original vault. + [System.ComponentModel.TypeConverter(typeof(DeletedVaultPropertiesTagsTypeConverter))] + public partial interface IDeletedVaultPropertiesTags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.TypeConverter.cs new file mode 100644 index 000000000000..8845364ddf30 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DeletedVaultPropertiesTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return DeletedVaultPropertiesTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return DeletedVaultPropertiesTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return DeletedVaultPropertiesTags.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/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.cs new file mode 100644 index 000000000000..d6054931264a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Tags of the original vault. + public partial class DeletedVaultPropertiesTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTagsInternal + { + + /// Creates an new instance. + public DeletedVaultPropertiesTags() + { + + } + } + /// Tags of the original vault. + public partial interface IDeletedVaultPropertiesTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// Tags of the original vault. + internal partial interface IDeletedVaultPropertiesTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.dictionary.cs new file mode 100644 index 000000000000..1d865a3bd57b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class DeletedVaultPropertiesTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.DeletedVaultPropertiesTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.json.cs new file mode 100644 index 000000000000..76a217ec28d1 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/DeletedVaultPropertiesTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Tags of the original vault. + public partial class DeletedVaultPropertiesTags + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal DeletedVaultPropertiesTags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IDeletedVaultPropertiesTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new DeletedVaultPropertiesTags(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.PowerShell.cs new file mode 100644 index 000000000000..93a1c15cb69c --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Permissions the identity has for keys, secrets, certificates and storage. + [System.ComponentModel.TypeConverter(typeof(PermissionsTypeConverter))] + public partial class Permissions + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Permissions(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.HanaOnAzure.Models.Api20161001.IPermissions DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Permissions(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.HanaOnAzure.Models.Api20161001.IPermissions FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Permissions(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Certificate = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[]) content.GetValueForProperty("Certificate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Certificate, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Key = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[]) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Key, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Secret = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[]) content.GetValueForProperty("Secret",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Secret, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Storage = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[]) content.GetValueForProperty("Storage",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Storage, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions.CreateFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Permissions(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Certificate = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[]) content.GetValueForProperty("Certificate",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Certificate, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Key = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[]) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Key, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Secret = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[]) content.GetValueForProperty("Secret",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Secret, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions.CreateFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Storage = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[]) content.GetValueForProperty("Storage",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal)this).Storage, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions.CreateFrom)); + 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Permissions the identity has for keys, secrets, certificates and storage. + [System.ComponentModel.TypeConverter(typeof(PermissionsTypeConverter))] + public partial interface IPermissions + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.TypeConverter.cs new file mode 100644 index 000000000000..11225d0c151b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PermissionsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Permissions.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Permissions.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Permissions.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/HanaOnAzure/generated/api/Models/Api20161001/Permissions.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.cs new file mode 100644 index 000000000000..9e3fbcafb6e4 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.cs @@ -0,0 +1,97 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Permissions the identity has for keys, secrets, certificates and storage. + public partial class Permissions : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissionsInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[] _certificate; + + /// Permissions to certificates + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[] Certificate { get => this._certificate; set => this._certificate = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[] _key; + + /// Permissions to keys + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[] Key { get => this._key; set => this._key = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[] _secret; + + /// Permissions to secrets + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[] Secret { get => this._secret; set => this._secret = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[] _storage; + + /// Permissions to storage accounts + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[] Storage { get => this._storage; set => this._storage = value; } + + /// Creates an new instance. + public Permissions() + { + + } + } + /// Permissions the identity has for keys, secrets, certificates and storage. + public partial interface IPermissions : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// Permissions to certificates + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to certificates", + SerializedName = @"certificates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[] Certificate { get; set; } + /// Permissions to keys + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to keys", + SerializedName = @"keys", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[] Key { get; set; } + /// Permissions to secrets + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to secrets", + SerializedName = @"secrets", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[] Secret { get; set; } + /// Permissions to storage accounts + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Permissions to storage accounts", + SerializedName = @"storage", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[] Storage { get; set; } + + } + /// Permissions the identity has for keys, secrets, certificates and storage. + internal partial interface IPermissionsInternal + + { + /// Permissions to certificates + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions[] Certificate { get; set; } + /// Permissions to keys + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions[] Key { get; set; } + /// Permissions to secrets + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions[] Secret { get; set; } + /// Permissions to storage accounts + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions[] Storage { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.json.cs new file mode 100644 index 000000000000..e1891be38a7a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Permissions.json.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Permissions the identity has for keys, secrets, certificates and storage. + public partial class Permissions + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IPermissions FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Permissions(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Permissions(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_certificate = If( json?.PropertyT("certificates"), out var __jsonCertificates) ? If( __jsonCertificates as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions) (__u is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString __t ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions)(__t.ToString()) : ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions)""))) ))() : null : Certificate;} + {_key = If( json?.PropertyT("keys"), out var __jsonKeys) ? If( __jsonKeys as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __q) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions) (__p is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString __o ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions)(__o.ToString()) : ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions)""))) ))() : null : Key;} + {_secret = If( json?.PropertyT("secrets"), out var __jsonSecrets) ? If( __jsonSecrets as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __l) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions) (__k is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString __j ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions)(__j.ToString()) : ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions)""))) ))() : null : Secret;} + {_storage = If( json?.PropertyT("storage"), out var __jsonStorage) ? If( __jsonStorage as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __g) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__g, (__f)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions) (__f is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString __e ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions)(__e.ToString()) : ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions)""))) ))() : null : Storage;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._certificate) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._certificate ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("certificates",__w); + } + if (null != this._key) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __s in this._key ) + { + AddIf(null != (((object)__s)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(__s.ToString()) : null ,__r.Add); + } + container.Add("keys",__r); + } + if (null != this._secret) + { + var __m = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __n in this._secret ) + { + AddIf(null != (((object)__n)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(__n.ToString()) : null ,__m.Add); + } + container.Add("secrets",__m); + } + if (null != this._storage) + { + var __h = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __i in this._storage ) + { + AddIf(null != (((object)__i)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(__i.ToString()) : null ,__h.Add); + } + container.Add("storage",__h); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.PowerShell.cs new file mode 100644 index 000000000000..a34b11bea6a3 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.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.HanaOnAzure.Models.Api20161001.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.HanaOnAzure.Models.Api20161001.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)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 Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.TypeConverter.cs new file mode 100644 index 000000000000..a9d7130af178 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.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/HanaOnAzure/generated/api/Models/Api20161001/Resource.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.cs new file mode 100644 index 000000000000..b761537e86c1 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.cs @@ -0,0 +1,99 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource(); + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The supported Azure location where the key vault should be created. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags _tag; + + /// The tags that will be assigned to the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTags()); set => this._tag = value; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; } + + /// Creates an new instance. + public Resource() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource + { + /// The supported Azure location where the key vault should be created. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The supported Azure location where the key vault should be created.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// The tags that will be assigned to the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The tags that will be assigned to the key vault. ", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags Tag { get; set; } + + } + internal partial interface IResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal + { + /// The supported Azure location where the key vault should be created. + string Location { get; set; } + /// The tags that will be assigned to the key vault. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.json.cs new file mode 100644 index 000000000000..2bc6e5823a73 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Resource.json.cs @@ -0,0 +1,104 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource(json); + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.PowerShell.cs new file mode 100644 index 000000000000..b44e79b31e98 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// List of vault resources. + [System.ComponentModel.TypeConverter(typeof(ResourceListResultTypeConverter))] + public partial class ResourceListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceListResult(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.HanaOnAzure.Models.Api20161001.IResourceListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceListResult(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.HanaOnAzure.Models.Api20161001.IResourceListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// List of vault resources. + [System.ComponentModel.TypeConverter(typeof(ResourceListResultTypeConverter))] + public partial interface IResourceListResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.TypeConverter.cs new file mode 100644 index 000000000000..abee1c9823c8 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceListResult.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/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.cs new file mode 100644 index 000000000000..2a8eb76c1f67 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of vault resources. + public partial class ResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to get the next set of vault resources. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource[] _value; + + /// The list of vault resources. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ResourceListResult() + { + + } + } + /// List of vault resources. + public partial interface IResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The URL to get the next set of vault resources. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to get the next set of vault resources.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of vault resources. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of vault resources.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource[] Value { get; set; } + + } + /// List of vault resources. + internal partial interface IResourceListResultInternal + + { + /// The URL to get the next set of vault resources. + string NextLink { get; set; } + /// The list of vault resources. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.json.cs new file mode 100644 index 000000000000..d658fac46ea7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of vault resources. + public partial class ResourceListResult + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new ResourceListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceListResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Resource.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.PowerShell.cs new file mode 100644 index 000000000000..2c33395c5e9a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The tags that will be assigned to the key vault. + [System.ComponentModel.TypeConverter(typeof(ResourceTagsTypeConverter))] + public partial class ResourceTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceTags(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceTags(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The tags that will be assigned to the key vault. + [System.ComponentModel.TypeConverter(typeof(ResourceTagsTypeConverter))] + public partial interface IResourceTags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.TypeConverter.cs new file mode 100644 index 000000000000..868fac2ed220 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceTags.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.cs new file mode 100644 index 000000000000..2433a1ac1d54 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The tags that will be assigned to the key vault. + public partial class ResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTagsInternal + { + + /// Creates an new instance. + public ResourceTags() + { + + } + } + /// The tags that will be assigned to the key vault. + public partial interface IResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// The tags that will be assigned to the key vault. + internal partial interface IResourceTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.dictionary.cs new file mode 100644 index 000000000000..cce0950d8b2c --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class ResourceTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.json.cs new file mode 100644 index 000000000000..08fbd6f0a605 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/ResourceTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The tags that will be assigned to the key vault. + public partial class ResourceTags + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new ResourceTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal ResourceTags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.PowerShell.cs new file mode 100644 index 000000000000..505e3ce9291f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// SKU details + [System.ComponentModel.TypeConverter(typeof(SkuTypeConverter))] + public partial class Sku + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Sku(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.HanaOnAzure.Models.Api20161001.ISku DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Sku(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.HanaOnAzure.Models.Api20161001.ISku FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Sku(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Name = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Name, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Family = (string) content.GetValueForProperty("Family",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Family, 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 Sku(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Name = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Name, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Family = (string) content.GetValueForProperty("Family",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)this).Family, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// SKU details + [System.ComponentModel.TypeConverter(typeof(SkuTypeConverter))] + public partial interface ISku + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.TypeConverter.cs new file mode 100644 index 000000000000..5dc93bdd12eb --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SkuTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Sku.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Sku.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Sku.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/HanaOnAzure/generated/api/Models/Api20161001/Sku.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.cs new file mode 100644 index 000000000000..4e4dadce329d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.cs @@ -0,0 +1,72 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// SKU details + public partial class Sku : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal + { + + /// Backing field for property. + private string _family= @"A"; + + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Family { get => this._family; } + + /// Internal Acessors for Family + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal.Family { get => this._family; set { {_family = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName _name; + + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public Sku() + { + + } + } + /// SKU details + public partial interface ISku : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"SKU family name", + SerializedName = @"family", + PossibleTypes = new [] { typeof(string) })] + string Family { get; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"SKU name to specify whether the key vault is a standard vault or a premium vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName Name { get; set; } + + } + /// SKU details + internal partial interface ISkuInternal + + { + /// SKU family name + string Family { get; set; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.json.cs new file mode 100644 index 000000000000..2c058b250461 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Sku.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// SKU details + public partial class Sku + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Sku(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Sku(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_family = If( json?.PropertyT("family"), out var __jsonFamily) ? (string)__jsonFamily : (string)Family;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._family)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._family.ToString()) : null, "family" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.PowerShell.cs new file mode 100644 index 000000000000..c0015a0a1d3b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.PowerShell.cs @@ -0,0 +1,165 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Resource information with extended details. + [System.ComponentModel.TypeConverter(typeof(VaultTypeConverter))] + public partial class Vault + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Vault(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.HanaOnAzure.Models.Api20161001.IVault DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Vault(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.HanaOnAzure.Models.Api20161001.IVault FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Vault(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuFamily, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Uri = (string) content.GetValueForProperty("Uri",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Uri, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Vault(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuFamily, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Uri = (string) content.GetValueForProperty("Uri",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).Uri, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + AfterDeserializePSObject(content); + } + } + /// Resource information with extended details. + [System.ComponentModel.TypeConverter(typeof(VaultTypeConverter))] + public partial interface IVault + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.TypeConverter.cs new file mode 100644 index 000000000000..9b5b034f728a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Vault.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Vault.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Vault.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/HanaOnAzure/generated/api/Models/Api20161001/Vault.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.cs new file mode 100644 index 000000000000..aef77d5c7c93 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.cs @@ -0,0 +1,329 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource information with extended details. + public partial class Vault : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Resource(); + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).AccessPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).AccessPolicy = value; } + + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).CreateMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).CreateMode = value; } + + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnablePurgeProtection { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnablePurgeProtection; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnablePurgeProtection = value; } + + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnableSoftDelete { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnableSoftDelete; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnableSoftDelete = value; } + + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForDeployment { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDeployment; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDeployment = value; } + + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForDiskEncryption { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDiskEncryption; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDiskEncryption = value; } + + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForTemplateDeployment { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForTemplateDeployment; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForTemplateDeployment = value; } + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; } + + /// The supported Azure location where the key vault should be created. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)__resource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)__resource).Location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties()); set { {_property = value;} } } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal.Sku { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).Sku; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).Sku = value; } + + /// Internal Acessors for SkuFamily + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultInternal.SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuFamily; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuFamily = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties _property; + + /// Properties of the vault + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties()); set => this._property = value; } + + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuFamily; } + + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuName; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuName = value; } + + /// The tags that will be assigned to the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)__resource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal)__resource).Tag = value; } + + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).TenantId = value; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; } + + /// The URI of the vault for performing operations on keys and secrets. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string Uri { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).VaultUri; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).VaultUri = value; } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + + /// Creates an new instance. + public Vault() + { + + } + } + /// Resource information with extended details. + public partial interface IVault : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResource + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access policies are required.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The vault's create mode to indicate whether the vault need to be recovered or not.", + SerializedName = @"createMode", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - that is, the property does not accept false as its value.", + SerializedName = @"enablePurgeProtection", + PossibleTypes = new [] { typeof(bool) })] + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality is irreversible - that is, the property does not accept false as its value.", + SerializedName = @"enableSoftDelete", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.", + SerializedName = @"enabledForDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.", + SerializedName = @"enabledForDiskEncryption", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.", + SerializedName = @"enabledForTemplateDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForTemplateDeployment { get; set; } + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"SKU family name", + SerializedName = @"family", + PossibleTypes = new [] { typeof(string) })] + string SkuFamily { get; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"SKU name to specify whether the key vault is a standard vault or a premium vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + /// The URI of the vault for performing operations on keys and secrets. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URI of the vault for performing operations on keys and secrets.", + SerializedName = @"vaultUri", + PossibleTypes = new [] { typeof(string) })] + string Uri { get; set; } + + } + /// Resource information with extended details. + internal partial interface IVaultInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IResourceInternal + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + bool? EnabledForTemplateDeployment { get; set; } + /// Properties of the vault + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties Property { get; set; } + /// SKU details + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Sku { get; set; } + /// SKU family name + string SkuFamily { get; set; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + string TenantId { get; set; } + /// The URI of the vault for performing operations on keys and secrets. + string Uri { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.json.cs new file mode 100644 index 000000000000..2ef7eafabf52 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/Vault.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource information with extended details. + public partial class Vault + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Vault(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Vault(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Resource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties.FromJson(__jsonProperties) : Property;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.PowerShell.cs new file mode 100644 index 000000000000..1681f3051951 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.PowerShell.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Parameters for updating the access policy in a vault + [System.ComponentModel.TypeConverter(typeof(VaultAccessPolicyParametersTypeConverter))] + public partial class VaultAccessPolicyParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultAccessPolicyParameters(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.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultAccessPolicyParameters(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.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultAccessPolicyParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultAccessPolicyParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + } + /// Parameters for updating the access policy in a vault + [System.ComponentModel.TypeConverter(typeof(VaultAccessPolicyParametersTypeConverter))] + public partial interface IVaultAccessPolicyParameters + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.TypeConverter.cs new file mode 100644 index 000000000000..7f61aebee3c2 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultAccessPolicyParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultAccessPolicyParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultAccessPolicyParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultAccessPolicyParameters.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/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.cs new file mode 100644 index 000000000000..14d435169d11 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.cs @@ -0,0 +1,144 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Parameters for updating the access policy in a vault + public partial class VaultAccessPolicyParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal + { + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyPropertiesInternal)Property).AccessPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyPropertiesInternal)Property).AccessPolicy = value; } + + /// Backing field for property. + private string _id; + + /// The resource id of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Backing field for property. + private string _location; + + /// The resource type of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Location + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal.Location { get => this._location; set { {_location = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyProperties()); set { {_property = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParametersInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The resource name of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties _property; + + /// Properties of the access policy + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyProperties()); set => this._property = value; } + + /// Backing field for property. + private string _type; + + /// The resource name of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public VaultAccessPolicyParameters() + { + + } + } + /// Parameters for updating the access policy in a vault + public partial interface IVaultAccessPolicyParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// The resource id of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource id of the access policy.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// The resource type of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource type of the access policy.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; } + /// The resource name of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource name of the access policy.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The resource name of the access policy. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The resource name of the access policy.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Parameters for updating the access policy in a vault + internal partial interface IVaultAccessPolicyParametersInternal + + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// The resource id of the access policy. + string Id { get; set; } + /// The resource type of the access policy. + string Location { get; set; } + /// The resource name of the access policy. + string Name { get; set; } + /// Properties of the access policy + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties Property { get; set; } + /// The resource name of the access policy. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.json.cs new file mode 100644 index 000000000000..1fcb3fd7511a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyParameters.json.cs @@ -0,0 +1,121 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Parameters for updating the access policy in a vault + public partial class VaultAccessPolicyParameters + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultAccessPolicyParameters(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultAccessPolicyParameters(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyProperties.FromJson(__jsonProperties) : Property;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.PowerShell.cs new file mode 100644 index 000000000000..9276f91ad1a1 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Properties of the vault access policy + [System.ComponentModel.TypeConverter(typeof(VaultAccessPolicyPropertiesTypeConverter))] + public partial class VaultAccessPolicyProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultAccessPolicyProperties(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.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultAccessPolicyProperties(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.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultAccessPolicyProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyPropertiesInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyPropertiesInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultAccessPolicyProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyPropertiesInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyPropertiesInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + } + /// Properties of the vault access policy + [System.ComponentModel.TypeConverter(typeof(VaultAccessPolicyPropertiesTypeConverter))] + public partial interface IVaultAccessPolicyProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.TypeConverter.cs new file mode 100644 index 000000000000..23809315e406 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultAccessPolicyPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultAccessPolicyProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultAccessPolicyProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultAccessPolicyProperties.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/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.cs new file mode 100644 index 000000000000..6085eac539c3 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.cs @@ -0,0 +1,55 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the vault access policy + public partial class VaultAccessPolicyProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] _accessPolicy; + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => this._accessPolicy; set => this._accessPolicy = value; } + + /// Creates an new instance. + public VaultAccessPolicyProperties() + { + + } + } + /// Properties of the vault access policy + public partial interface IVaultAccessPolicyProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + + } + /// Properties of the vault access policy + internal partial interface IVaultAccessPolicyPropertiesInternal + + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.json.cs new file mode 100644 index 000000000000..4a16d51f6323 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultAccessPolicyProperties.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the vault access policy + public partial class VaultAccessPolicyProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultAccessPolicyProperties(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._accessPolicy) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._accessPolicy ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("accessPolicies",__w); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultAccessPolicyProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_accessPolicy = If( json?.PropertyT("accessPolicies"), out var __jsonAccessPolicies) ? If( __jsonAccessPolicies as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntry.FromJson(__u) )) ))() : null : AccessPolicy;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.PowerShell.cs new file mode 100644 index 000000000000..f63f23bfa9e9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The parameters used to check the availability of the vault name. + [System.ComponentModel.TypeConverter(typeof(VaultCheckNameAvailabilityParametersTypeConverter))] + public partial class VaultCheckNameAvailabilityParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultCheckNameAvailabilityParameters(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.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultCheckNameAvailabilityParameters(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.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultCheckNameAvailabilityParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)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 VaultCheckNameAvailabilityParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal)this).Type, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + } + /// The parameters used to check the availability of the vault name. + [System.ComponentModel.TypeConverter(typeof(VaultCheckNameAvailabilityParametersTypeConverter))] + public partial interface IVaultCheckNameAvailabilityParameters + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.TypeConverter.cs new file mode 100644 index 000000000000..1c0799cc6f5a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.TypeConverter.cs @@ -0,0 +1,144 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultCheckNameAvailabilityParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultCheckNameAvailabilityParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultCheckNameAvailabilityParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultCheckNameAvailabilityParameters.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/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.cs new file mode 100644 index 000000000000..3a85d30058d9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.cs @@ -0,0 +1,66 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The parameters used to check the availability of the vault name. + public partial class VaultCheckNameAvailabilityParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal + { + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParametersInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The vault name. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _type= @"Microsoft.KeyVault/vaults"; + + /// The type of resource, Microsoft.KeyVault/vaults + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public VaultCheckNameAvailabilityParameters() + { + + } + } + /// The parameters used to check the availability of the vault name. + public partial interface IVaultCheckNameAvailabilityParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The vault name. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The vault name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// The type of resource, Microsoft.KeyVault/vaults + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"The type of resource, Microsoft.KeyVault/vaults", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The parameters used to check the availability of the vault name. + internal partial interface IVaultCheckNameAvailabilityParametersInternal + + { + /// The vault name. + string Name { get; set; } + /// The type of resource, Microsoft.KeyVault/vaults + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.json.cs new file mode 100644 index 000000000000..5d9a71b901af --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCheckNameAvailabilityParameters.json.cs @@ -0,0 +1,104 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The parameters used to check the availability of the vault name. + public partial class VaultCheckNameAvailabilityParameters + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCheckNameAvailabilityParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultCheckNameAvailabilityParameters(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultCheckNameAvailabilityParameters(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.PowerShell.cs new file mode 100644 index 000000000000..01feb533341a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.PowerShell.cs @@ -0,0 +1,161 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Parameters for creating or updating a vault + [System.ComponentModel.TypeConverter(typeof(VaultCreateOrUpdateParametersTypeConverter))] + public partial class VaultCreateOrUpdateParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultCreateOrUpdateParameters(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.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultCreateOrUpdateParameters(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.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultCreateOrUpdateParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParametersTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuFamily, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).VaultUri = (string) content.GetValueForProperty("VaultUri",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).VaultUri, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultCreateOrUpdateParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParametersTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuFamily, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).VaultUri = (string) content.GetValueForProperty("VaultUri",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).VaultUri, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + AfterDeserializePSObject(content); + } + } + /// Parameters for creating or updating a vault + [System.ComponentModel.TypeConverter(typeof(VaultCreateOrUpdateParametersTypeConverter))] + public partial interface IVaultCreateOrUpdateParameters + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.TypeConverter.cs new file mode 100644 index 000000000000..569c4f4c5079 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultCreateOrUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultCreateOrUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultCreateOrUpdateParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultCreateOrUpdateParameters.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/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.cs new file mode 100644 index 000000000000..5905f6f0685e --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.cs @@ -0,0 +1,315 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Parameters for creating or updating a vault + public partial class VaultCreateOrUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal + { + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).AccessPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).AccessPolicy = value; } + + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).CreateMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).CreateMode = value; } + + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnablePurgeProtection { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnablePurgeProtection; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnablePurgeProtection = value; } + + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnableSoftDelete { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnableSoftDelete; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnableSoftDelete = value; } + + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForDeployment { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDeployment; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDeployment = value; } + + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForDiskEncryption { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDiskEncryption; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForDiskEncryption = value; } + + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForTemplateDeployment { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForTemplateDeployment; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).EnabledForTemplateDeployment = value; } + + /// Backing field for property. + private string _location; + + /// The supported Azure location where the key vault should be created. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties()); set { {_property = value;} } } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal.Sku { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).Sku; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).Sku = value; } + + /// Internal Acessors for SkuFamily + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersInternal.SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuFamily; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuFamily = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties _property; + + /// Properties of the vault + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties()); set => this._property = value; } + + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuFamily; } + + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuName; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).SkuName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags _tag; + + /// The tags that will be assigned to the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParametersTags()); set => this._tag = value; } + + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).TenantId = value; } + + /// The URI of the vault for performing operations on keys and secrets. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string VaultUri { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).VaultUri; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)Property).VaultUri = value; } + + /// Creates an new instance. + public VaultCreateOrUpdateParameters() + { + + } + } + /// Parameters for creating or updating a vault + public partial interface IVaultCreateOrUpdateParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access policies are required.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The vault's create mode to indicate whether the vault need to be recovered or not.", + SerializedName = @"createMode", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - that is, the property does not accept false as its value.", + SerializedName = @"enablePurgeProtection", + PossibleTypes = new [] { typeof(bool) })] + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality is irreversible - that is, the property does not accept false as its value.", + SerializedName = @"enableSoftDelete", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.", + SerializedName = @"enabledForDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.", + SerializedName = @"enabledForDiskEncryption", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.", + SerializedName = @"enabledForTemplateDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForTemplateDeployment { get; set; } + /// The supported Azure location where the key vault should be created. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The supported Azure location where the key vault should be created.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"SKU family name", + SerializedName = @"family", + PossibleTypes = new [] { typeof(string) })] + string SkuFamily { get; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"SKU name to specify whether the key vault is a standard vault or a premium vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// The tags that will be assigned to the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The tags that will be assigned to the key vault.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags Tag { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + /// The URI of the vault for performing operations on keys and secrets. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URI of the vault for performing operations on keys and secrets.", + SerializedName = @"vaultUri", + PossibleTypes = new [] { typeof(string) })] + string VaultUri { get; set; } + + } + /// Parameters for creating or updating a vault + internal partial interface IVaultCreateOrUpdateParametersInternal + + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + bool? EnabledForTemplateDeployment { get; set; } + /// The supported Azure location where the key vault should be created. + string Location { get; set; } + /// Properties of the vault + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties Property { get; set; } + /// SKU details + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Sku { get; set; } + /// SKU family name + string SkuFamily { get; set; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// The tags that will be assigned to the key vault. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags Tag { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + string TenantId { get; set; } + /// The URI of the vault for performing operations on keys and secrets. + string VaultUri { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.json.cs new file mode 100644 index 000000000000..ab038b7374fd --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParameters.json.cs @@ -0,0 +1,105 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Parameters for creating or updating a vault + public partial class VaultCreateOrUpdateParameters + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultCreateOrUpdateParameters(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultCreateOrUpdateParameters(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultProperties.FromJson(__jsonProperties) : Property;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParametersTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.PowerShell.cs new file mode 100644 index 000000000000..c2255d790c7c --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The tags that will be assigned to the key vault. + [System.ComponentModel.TypeConverter(typeof(VaultCreateOrUpdateParametersTagsTypeConverter))] + public partial class VaultCreateOrUpdateParametersTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultCreateOrUpdateParametersTags(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.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultCreateOrUpdateParametersTags(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.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultCreateOrUpdateParametersTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultCreateOrUpdateParametersTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// The tags that will be assigned to the key vault. + [System.ComponentModel.TypeConverter(typeof(VaultCreateOrUpdateParametersTagsTypeConverter))] + public partial interface IVaultCreateOrUpdateParametersTags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.TypeConverter.cs new file mode 100644 index 000000000000..af327bb5f4e1 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultCreateOrUpdateParametersTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultCreateOrUpdateParametersTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultCreateOrUpdateParametersTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultCreateOrUpdateParametersTags.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/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.cs new file mode 100644 index 000000000000..bcbc43bb0bc3 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The tags that will be assigned to the key vault. + public partial class VaultCreateOrUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTagsInternal + { + + /// Creates an new instance. + public VaultCreateOrUpdateParametersTags() + { + + } + } + /// The tags that will be assigned to the key vault. + public partial interface IVaultCreateOrUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// The tags that will be assigned to the key vault. + internal partial interface IVaultCreateOrUpdateParametersTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.dictionary.cs new file mode 100644 index 000000000000..3163ef6d00b4 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class VaultCreateOrUpdateParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultCreateOrUpdateParametersTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.json.cs new file mode 100644 index 000000000000..bf3478943931 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultCreateOrUpdateParametersTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The tags that will be assigned to the key vault. + public partial class VaultCreateOrUpdateParametersTags + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultCreateOrUpdateParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultCreateOrUpdateParametersTags(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal VaultCreateOrUpdateParametersTags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.PowerShell.cs new file mode 100644 index 000000000000..40f08aefe61f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// List of vaults + [System.ComponentModel.TypeConverter(typeof(VaultListResultTypeConverter))] + public partial class VaultListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultListResult(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.HanaOnAzure.Models.Api20161001.IVaultListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultListResult(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.HanaOnAzure.Models.Api20161001.IVaultListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + } + /// List of vaults + [System.ComponentModel.TypeConverter(typeof(VaultListResultTypeConverter))] + public partial interface IVaultListResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.TypeConverter.cs new file mode 100644 index 000000000000..d3b610bde8cb --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultListResult.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/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.cs new file mode 100644 index 000000000000..1eb9c585a210 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of vaults + public partial class VaultListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to get the next set of vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault[] _value; + + /// The list of vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public VaultListResult() + { + + } + } + /// List of vaults + public partial interface IVaultListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The URL to get the next set of vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to get the next set of vaults.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of vaults. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of vaults.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault[] Value { get; set; } + + } + /// List of vaults + internal partial interface IVaultListResultInternal + + { + /// The URL to get the next set of vaults. + string NextLink { get; set; } + /// The list of vaults. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.json.cs new file mode 100644 index 000000000000..601632b44cfe --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of vaults + public partial class VaultListResult + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultListResult(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultListResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVault) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Vault.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.PowerShell.cs new file mode 100644 index 000000000000..139987fc3d58 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.PowerShell.cs @@ -0,0 +1,155 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Parameters for creating or updating a vault + [System.ComponentModel.TypeConverter(typeof(VaultPatchParametersTypeConverter))] + public partial class VaultPatchParameters + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultPatchParameters(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.HanaOnAzure.Models.Api20161001.IVaultPatchParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultPatchParameters(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.HanaOnAzure.Models.Api20161001.IVaultPatchParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultPatchParameters(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchParametersTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuFamily, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultPatchParameters(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchParametersTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuFamily, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + AfterDeserializePSObject(content); + } + } + /// Parameters for creating or updating a vault + [System.ComponentModel.TypeConverter(typeof(VaultPatchParametersTypeConverter))] + public partial interface IVaultPatchParameters + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.TypeConverter.cs new file mode 100644 index 000000000000..e149fc018617 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultPatchParametersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultPatchParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultPatchParameters.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultPatchParameters.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/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.cs new file mode 100644 index 000000000000..caa2ca8b3be2 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.cs @@ -0,0 +1,272 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Parameters for creating or updating a vault + public partial class VaultPatchParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal + { + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).AccessPolicy; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).AccessPolicy = value; } + + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).CreateMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).CreateMode = value; } + + /// + /// Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is + /// also enabled. Once activated, the property may no longer be reset to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnablePurgeProtection { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnablePurgeProtection; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnablePurgeProtection = value; } + + /// + /// Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be + /// set to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnableSoftDelete { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnableSoftDelete; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnableSoftDelete = value; } + + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForDeployment { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnabledForDeployment; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnabledForDeployment = value; } + + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForDiskEncryption { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnabledForDiskEncryption; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnabledForDiskEncryption = value; } + + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public bool? EnabledForTemplateDeployment { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnabledForTemplateDeployment; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).EnabledForTemplateDeployment = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchProperties()); set { {_property = value;} } } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal.Sku { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).Sku; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).Sku = value; } + + /// Internal Acessors for SkuFamily + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersInternal.SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).SkuFamily; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).SkuFamily = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties _property; + + /// Properties of the vault + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchProperties()); set => this._property = value; } + + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).SkuFamily; } + + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).SkuName; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).SkuName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags _tag; + + /// The tags that will be assigned to the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchParametersTags()); set => this._tag = value; } + + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)Property).TenantId = value; } + + /// Creates an new instance. + public VaultPatchParameters() + { + + } + } + /// Parameters for creating or updating a vault + public partial interface IVaultPatchParameters : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The vault's create mode to indicate whether the vault need to be recovered or not.", + SerializedName = @"createMode", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is + /// also enabled. Once activated, the property may no longer be reset to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is also enabled. Once activated, the property may no longer be reset to false.", + SerializedName = @"enablePurgeProtection", + PossibleTypes = new [] { typeof(bool) })] + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be + /// set to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be set to false.", + SerializedName = @"enableSoftDelete", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.", + SerializedName = @"enabledForDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.", + SerializedName = @"enabledForDiskEncryption", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.", + SerializedName = @"enabledForTemplateDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForTemplateDeployment { get; set; } + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"SKU family name", + SerializedName = @"family", + PossibleTypes = new [] { typeof(string) })] + string SkuFamily { get; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"SKU name to specify whether the key vault is a standard vault or a premium vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// The tags that will be assigned to the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The tags that will be assigned to the key vault. ", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags Tag { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + + } + /// Parameters for creating or updating a vault + internal partial interface IVaultPatchParametersInternal + + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is + /// also enabled. Once activated, the property may no longer be reset to false. + /// + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be + /// set to false. + /// + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + bool? EnabledForTemplateDeployment { get; set; } + /// Properties of the vault + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties Property { get; set; } + /// SKU details + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Sku { get; set; } + /// SKU family name + string SkuFamily { get; set; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// The tags that will be assigned to the key vault. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags Tag { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.json.cs new file mode 100644 index 000000000000..046aeb99fb77 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParameters.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Parameters for creating or updating a vault + public partial class VaultPatchParameters + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParameters FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultPatchParameters(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultPatchParameters(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchProperties.FromJson(__jsonProperties) : Property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchParametersTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.PowerShell.cs new file mode 100644 index 000000000000..900bad7fd188 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The tags that will be assigned to the key vault. + [System.ComponentModel.TypeConverter(typeof(VaultPatchParametersTagsTypeConverter))] + public partial class VaultPatchParametersTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultPatchParametersTags(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.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultPatchParametersTags(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.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultPatchParametersTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal VaultPatchParametersTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + } + /// The tags that will be assigned to the key vault. + [System.ComponentModel.TypeConverter(typeof(VaultPatchParametersTagsTypeConverter))] + public partial interface IVaultPatchParametersTags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.TypeConverter.cs new file mode 100644 index 000000000000..5557bddd61c0 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultPatchParametersTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultPatchParametersTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultPatchParametersTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultPatchParametersTags.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/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.cs new file mode 100644 index 000000000000..a49db8e685ec --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The tags that will be assigned to the key vault. + public partial class VaultPatchParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTagsInternal + { + + /// Creates an new instance. + public VaultPatchParametersTags() + { + + } + } + /// The tags that will be assigned to the key vault. + public partial interface IVaultPatchParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// The tags that will be assigned to the key vault. + internal partial interface IVaultPatchParametersTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.dictionary.cs new file mode 100644 index 000000000000..27cf234f215d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class VaultPatchParametersTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultPatchParametersTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.json.cs new file mode 100644 index 000000000000..fc96c25bbc02 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchParametersTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The tags that will be assigned to the key vault. + public partial class VaultPatchParametersTags + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchParametersTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultPatchParametersTags(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal VaultPatchParametersTags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.PowerShell.cs new file mode 100644 index 000000000000..c8386139409f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.PowerShell.cs @@ -0,0 +1,151 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Properties of the vault + [System.ComponentModel.TypeConverter(typeof(VaultPatchPropertiesTypeConverter))] + public partial class VaultPatchProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultPatchProperties(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.HanaOnAzure.Models.Api20161001.IVaultPatchProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultPatchProperties(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.HanaOnAzure.Models.Api20161001.IVaultPatchProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultPatchProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuFamily, 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 VaultPatchProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal)this).SkuFamily, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + } + /// Properties of the vault + [System.ComponentModel.TypeConverter(typeof(VaultPatchPropertiesTypeConverter))] + public partial interface IVaultPatchProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.TypeConverter.cs new file mode 100644 index 000000000000..fbd7ff92edc4 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultPatchPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultPatchProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultPatchProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultPatchProperties.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/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.cs new file mode 100644 index 000000000000..3a34db9c72b6 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.cs @@ -0,0 +1,274 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the vault + public partial class VaultPatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] _accessPolicy; + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => this._accessPolicy; set => this._accessPolicy = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? _createMode; + + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get => this._createMode; set => this._createMode = value; } + + /// Backing field for property. + private bool? _enablePurgeProtection; + + /// + /// Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is + /// also enabled. Once activated, the property may no longer be reset to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnablePurgeProtection { get => this._enablePurgeProtection; set => this._enablePurgeProtection = value; } + + /// Backing field for property. + private bool? _enableSoftDelete; + + /// + /// Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be + /// set to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnableSoftDelete { get => this._enableSoftDelete; set => this._enableSoftDelete = value; } + + /// Backing field for property. + private bool? _enabledForDeployment; + + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnabledForDeployment { get => this._enabledForDeployment; set => this._enabledForDeployment = value; } + + /// Backing field for property. + private bool? _enabledForDiskEncryption; + + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnabledForDiskEncryption { get => this._enabledForDiskEncryption; set => this._enabledForDiskEncryption = value; } + + /// Backing field for property. + private bool? _enabledForTemplateDeployment; + + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnabledForTemplateDeployment { get => this._enabledForTemplateDeployment; set => this._enabledForTemplateDeployment = value; } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal.Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku()); set { {_sku = value;} } } + + /// Internal Acessors for SkuFamily + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchPropertiesInternal.SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Family; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Family = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku _sku; + + /// SKU details + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku()); set => this._sku = value; } + + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Family; } + + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Name = value; } + + /// Backing field for property. + private string _tenantId; + + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; set => this._tenantId = value; } + + /// Creates an new instance. + public VaultPatchProperties() + { + + } + } + /// Properties of the vault + public partial interface IVaultPatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The vault's create mode to indicate whether the vault need to be recovered or not.", + SerializedName = @"createMode", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is + /// also enabled. Once activated, the property may no longer be reset to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is also enabled. Once activated, the property may no longer be reset to false.", + SerializedName = @"enablePurgeProtection", + PossibleTypes = new [] { typeof(bool) })] + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be + /// set to false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be set to false.", + SerializedName = @"enableSoftDelete", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.", + SerializedName = @"enabledForDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.", + SerializedName = @"enabledForDiskEncryption", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.", + SerializedName = @"enabledForTemplateDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForTemplateDeployment { get; set; } + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"SKU family name", + SerializedName = @"family", + PossibleTypes = new [] { typeof(string) })] + string SkuFamily { get; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"SKU name to specify whether the key vault is a standard vault or a premium vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + + } + /// Properties of the vault + internal partial interface IVaultPatchPropertiesInternal + + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault; it is only effective if soft delete is + /// also enabled. Once activated, the property may no longer be reset to false. + /// + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion ('soft' delete) is enabled for this key vault. The property may not be + /// set to false. + /// + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + bool? EnabledForTemplateDeployment { get; set; } + /// SKU details + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Sku { get; set; } + /// SKU family name + string SkuFamily { get; set; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.json.cs new file mode 100644 index 000000000000..284078def3f9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultPatchProperties.json.cs @@ -0,0 +1,125 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the vault + public partial class VaultPatchProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPatchProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultPatchProperties(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add ); + if (null != this._accessPolicy) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._accessPolicy ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("accessPolicies",__w); + } + AddIf( null != (((object)this._createMode)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._createMode.ToString()) : null, "createMode" ,container.Add ); + AddIf( null != this._enablePurgeProtection ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enablePurgeProtection) : null, "enablePurgeProtection" ,container.Add ); + AddIf( null != this._enableSoftDelete ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enableSoftDelete) : null, "enableSoftDelete" ,container.Add ); + AddIf( null != this._enabledForDeployment ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enabledForDeployment) : null, "enabledForDeployment" ,container.Add ); + AddIf( null != this._enabledForDiskEncryption ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enabledForDiskEncryption) : null, "enabledForDiskEncryption" ,container.Add ); + AddIf( null != this._enabledForTemplateDeployment ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enabledForTemplateDeployment) : null, "enabledForTemplateDeployment" ,container.Add ); + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultPatchProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_sku = If( json?.PropertyT("sku"), out var __jsonSku) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku.FromJson(__jsonSku) : Sku;} + {_accessPolicy = If( json?.PropertyT("accessPolicies"), out var __jsonAccessPolicies) ? If( __jsonAccessPolicies as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntry.FromJson(__u) )) ))() : null : AccessPolicy;} + {_createMode = If( json?.PropertyT("createMode"), out var __jsonCreateMode) ? (string)__jsonCreateMode : (string)CreateMode;} + {_enablePurgeProtection = If( json?.PropertyT("enablePurgeProtection"), out var __jsonEnablePurgeProtection) ? (bool?)__jsonEnablePurgeProtection : EnablePurgeProtection;} + {_enableSoftDelete = If( json?.PropertyT("enableSoftDelete"), out var __jsonEnableSoftDelete) ? (bool?)__jsonEnableSoftDelete : EnableSoftDelete;} + {_enabledForDeployment = If( json?.PropertyT("enabledForDeployment"), out var __jsonEnabledForDeployment) ? (bool?)__jsonEnabledForDeployment : EnabledForDeployment;} + {_enabledForDiskEncryption = If( json?.PropertyT("enabledForDiskEncryption"), out var __jsonEnabledForDiskEncryption) ? (bool?)__jsonEnabledForDiskEncryption : EnabledForDiskEncryption;} + {_enabledForTemplateDeployment = If( json?.PropertyT("enabledForTemplateDeployment"), out var __jsonEnabledForTemplateDeployment) ? (bool?)__jsonEnabledForTemplateDeployment : EnabledForTemplateDeployment;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)TenantId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.PowerShell.cs new file mode 100644 index 000000000000..6e67016332b3 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.PowerShell.cs @@ -0,0 +1,153 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Properties of the vault + [System.ComponentModel.TypeConverter(typeof(VaultPropertiesTypeConverter))] + public partial class VaultProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VaultProperties(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.HanaOnAzure.Models.Api20161001.IVaultProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VaultProperties(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.HanaOnAzure.Models.Api20161001.IVaultProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VaultProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).VaultUri = (string) content.GetValueForProperty("VaultUri",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).VaultUri, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuFamily, 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 VaultProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.SkuTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).AccessPolicy = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]) content.GetValueForProperty("AccessPolicy",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).AccessPolicy, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntryTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode?) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnablePurgeProtection = (bool?) content.GetValueForProperty("EnablePurgeProtection",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnablePurgeProtection, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnableSoftDelete = (bool?) content.GetValueForProperty("EnableSoftDelete",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnableSoftDelete, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDeployment = (bool?) content.GetValueForProperty("EnabledForDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDiskEncryption = (bool?) content.GetValueForProperty("EnabledForDiskEncryption",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForDiskEncryption, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForTemplateDeployment = (bool?) content.GetValueForProperty("EnabledForTemplateDeployment",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).EnabledForTemplateDeployment, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).TenantId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).VaultUri = (string) content.GetValueForProperty("VaultUri",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).VaultUri, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuName = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuName, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal)this).SkuFamily, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + } + /// Properties of the vault + [System.ComponentModel.TypeConverter(typeof(VaultPropertiesTypeConverter))] + public partial interface IVaultProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.TypeConverter.cs new file mode 100644 index 000000000000..7575c22921b1 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VaultPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VaultProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VaultProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VaultProperties.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/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.cs new file mode 100644 index 000000000000..249f5fc17ebd --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.cs @@ -0,0 +1,303 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the vault + public partial class VaultProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] _accessPolicy; + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => this._accessPolicy; set => this._accessPolicy = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? _createMode; + + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get => this._createMode; set => this._createMode = value; } + + /// Backing field for property. + private bool? _enablePurgeProtection; + + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnablePurgeProtection { get => this._enablePurgeProtection; set => this._enablePurgeProtection = value; } + + /// Backing field for property. + private bool? _enableSoftDelete; + + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnableSoftDelete { get => this._enableSoftDelete; set => this._enableSoftDelete = value; } + + /// Backing field for property. + private bool? _enabledForDeployment; + + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnabledForDeployment { get => this._enabledForDeployment; set => this._enabledForDeployment = value; } + + /// Backing field for property. + private bool? _enabledForDiskEncryption; + + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnabledForDiskEncryption { get => this._enabledForDiskEncryption; set => this._enabledForDiskEncryption = value; } + + /// Backing field for property. + private bool? _enabledForTemplateDeployment; + + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnabledForTemplateDeployment { get => this._enabledForTemplateDeployment; set => this._enabledForTemplateDeployment = value; } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal.Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku()); set { {_sku = value;} } } + + /// Internal Acessors for SkuFamily + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultPropertiesInternal.SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Family; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Family = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku _sku; + + /// SKU details + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku()); set => this._sku = value; } + + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string SkuFamily { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Family; } + + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISkuInternal)Sku).Name = value; } + + /// Backing field for property. + private string _tenantId; + + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; set => this._tenantId = value; } + + /// Backing field for property. + private string _vaultUri; + + /// The URI of the vault for performing operations on keys and secrets. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string VaultUri { get => this._vaultUri; set => this._vaultUri = value; } + + /// Creates an new instance. + public VaultProperties() + { + + } + } + /// Properties of the vault + public partial interface IVaultProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access policies are required.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The vault's create mode to indicate whether the vault need to be recovered or not.", + SerializedName = @"createMode", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - that is, the property does not accept false as its value.", + SerializedName = @"enablePurgeProtection", + PossibleTypes = new [] { typeof(bool) })] + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality is irreversible - that is, the property does not accept false as its value.", + SerializedName = @"enableSoftDelete", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.", + SerializedName = @"enabledForDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.", + SerializedName = @"enabledForDiskEncryption", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.", + SerializedName = @"enabledForTemplateDeployment", + PossibleTypes = new [] { typeof(bool) })] + bool? EnabledForTemplateDeployment { get; set; } + /// SKU family name + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = true, + Description = @"SKU family name", + SerializedName = @"family", + PossibleTypes = new [] { typeof(string) })] + string SkuFamily { get; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"SKU name to specify whether the key vault is a standard vault or a premium vault.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; set; } + /// The URI of the vault for performing operations on keys and secrets. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URI of the vault for performing operations on keys and secrets.", + SerializedName = @"vaultUri", + PossibleTypes = new [] { typeof(string) })] + string VaultUri { get; set; } + + } + /// Properties of the vault + internal partial interface IVaultPropertiesInternal + + { + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. When `createMode` is set to `recover`, access policies are not required. Otherwise, access + /// policies are required. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get; set; } + /// + /// The vault's create mode to indicate whether the vault need to be recovered or not. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode? CreateMode { get; set; } + /// + /// Property specifying whether protection against purge is enabled for this vault. Setting this property to true activates + /// protection against purge for this vault and its content - only the Key Vault service may initiate a hard, irrecoverable + /// deletion. The setting is effective only if soft delete is also enabled. Enabling this functionality is irreversible - + /// that is, the property does not accept false as its value. + /// + bool? EnablePurgeProtection { get; set; } + /// + /// Property specifying whether recoverable deletion is enabled for this key vault. Setting this property to true activates + /// the soft delete feature, whereby vaults or vault entities can be recovered after deletion. Enabling this functionality + /// is irreversible - that is, the property does not accept false as its value. + /// + bool? EnableSoftDelete { get; set; } + /// + /// Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key + /// vault. + /// + bool? EnabledForDeployment { get; set; } + /// + /// Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. + /// + bool? EnabledForDiskEncryption { get; set; } + /// + /// Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. + /// + bool? EnabledForTemplateDeployment { get; set; } + /// SKU details + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.ISku Sku { get; set; } + /// SKU family name + string SkuFamily { get; set; } + /// + /// SKU name to specify whether the key vault is a standard vault or a premium vault. + /// + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName SkuName { get; set; } + /// + /// The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + /// + string TenantId { get; set; } + /// The URI of the vault for performing operations on keys and secrets. + string VaultUri { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.json.cs new file mode 100644 index 000000000000..8d6f4c8c6a51 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20161001/VaultProperties.json.cs @@ -0,0 +1,127 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Properties of the vault + public partial class VaultProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new VaultProperties(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add ); + if (null != this._accessPolicy) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._accessPolicy ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("accessPolicies",__w); + } + AddIf( null != (((object)this._createMode)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._createMode.ToString()) : null, "createMode" ,container.Add ); + AddIf( null != this._enablePurgeProtection ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enablePurgeProtection) : null, "enablePurgeProtection" ,container.Add ); + AddIf( null != this._enableSoftDelete ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enableSoftDelete) : null, "enableSoftDelete" ,container.Add ); + AddIf( null != this._enabledForDeployment ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enabledForDeployment) : null, "enabledForDeployment" ,container.Add ); + AddIf( null != this._enabledForDiskEncryption ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enabledForDiskEncryption) : null, "enabledForDiskEncryption" ,container.Add ); + AddIf( null != this._enabledForTemplateDeployment ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enabledForTemplateDeployment) : null, "enabledForTemplateDeployment" ,container.Add ); + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + AddIf( null != (((object)this._vaultUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._vaultUri.ToString()) : null, "vaultUri" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal VaultProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_sku = If( json?.PropertyT("sku"), out var __jsonSku) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.Sku.FromJson(__jsonSku) : Sku;} + {_accessPolicy = If( json?.PropertyT("accessPolicies"), out var __jsonAccessPolicies) ? If( __jsonAccessPolicies as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.AccessPolicyEntry.FromJson(__u) )) ))() : null : AccessPolicy;} + {_createMode = If( json?.PropertyT("createMode"), out var __jsonCreateMode) ? (string)__jsonCreateMode : (string)CreateMode;} + {_enablePurgeProtection = If( json?.PropertyT("enablePurgeProtection"), out var __jsonEnablePurgeProtection) ? (bool?)__jsonEnablePurgeProtection : EnablePurgeProtection;} + {_enableSoftDelete = If( json?.PropertyT("enableSoftDelete"), out var __jsonEnableSoftDelete) ? (bool?)__jsonEnableSoftDelete : EnableSoftDelete;} + {_enabledForDeployment = If( json?.PropertyT("enabledForDeployment"), out var __jsonEnabledForDeployment) ? (bool?)__jsonEnabledForDeployment : EnabledForDeployment;} + {_enabledForDiskEncryption = If( json?.PropertyT("enabledForDiskEncryption"), out var __jsonEnabledForDiskEncryption) ? (bool?)__jsonEnabledForDiskEncryption : EnabledForDiskEncryption;} + {_enabledForTemplateDeployment = If( json?.PropertyT("enabledForTemplateDeployment"), out var __jsonEnabledForTemplateDeployment) ? (bool?)__jsonEnabledForTemplateDeployment : EnabledForTemplateDeployment;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)TenantId;} + {_vaultUri = If( json?.PropertyT("vaultUri"), out var __jsonVaultUri) ? (string)__jsonVaultUri : (string)VaultUri;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.PowerShell.cs new file mode 100644 index 000000000000..5eaea435b1ed --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// An error response from the ManagedServiceIdentity service. + [System.ComponentModel.TypeConverter(typeof(CloudErrorTypeConverter))] + public partial class CloudError + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CloudError(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBodyTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Target, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBodyTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CloudError(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBodyTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Target, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBodyTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudError DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CloudError(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.HanaOnAzure.Models.Api20181130.ICloudError DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CloudError(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.HanaOnAzure.Models.Api20181130.ICloudError FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// An error response from the ManagedServiceIdentity service. + [System.ComponentModel.TypeConverter(typeof(CloudErrorTypeConverter))] + public partial interface ICloudError + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.TypeConverter.cs new file mode 100644 index 000000000000..bcbf5ae87e37 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CloudErrorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudError ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudError).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CloudError.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CloudError.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CloudError.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/HanaOnAzure/generated/api/Models/Api20181130/CloudError.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.cs new file mode 100644 index 000000000000..30c6c73b3507 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// An error response from the ManagedServiceIdentity service. + public partial class CloudError : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudError, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal + { + + /// An identifier for the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Code = value; } + + /// A list of additional details about the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[] Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Detail = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody _error; + + /// A list of additional details about the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBody()); set => this._error = value; } + + /// + /// A message describing the error, intended to be suitable for display in a user interface. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Message = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBody()); set { {_error = value;} } } + + /// + /// The target of the particular error. For example, the name of the property in error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)Error).Target = value; } + + /// Creates an new instance. + public CloudError() + { + + } + } + /// An error response from the ManagedServiceIdentity service. + public partial interface ICloudError : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// An identifier for the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"An identifier for the error.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// A list of additional details about the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of additional details about the error.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[] Detail { get; set; } + /// + /// A message describing the error, intended to be suitable for display in a user interface. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A message describing the error, intended to be suitable for display in a user interface.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + /// + /// The target of the particular error. For example, the name of the property in error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The target of the particular error. For example, the name of the property in error.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; set; } + + } + /// An error response from the ManagedServiceIdentity service. + internal partial interface ICloudErrorInternal + + { + /// An identifier for the error. + string Code { get; set; } + /// A list of additional details about the error. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[] Detail { get; set; } + /// A list of additional details about the error. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody Error { get; set; } + /// + /// A message describing the error, intended to be suitable for display in a user interface. + /// + string Message { get; set; } + /// + /// The target of the particular error. For example, the name of the property in error. + /// + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.json.cs new file mode 100644 index 000000000000..2ce2266b324b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudError.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// An error response from the ManagedServiceIdentity service. + public partial class CloudError + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal CloudError(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Models.Api20181130.CloudErrorBody.FromJson(__jsonError) : Error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudError. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudError. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudError FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new CloudError(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.PowerShell.cs new file mode 100644 index 000000000000..21f59a08baaf --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// An error response from the ManagedServiceIdentity service. + [System.ComponentModel.TypeConverter(typeof(CloudErrorBodyTypeConverter))] + public partial class CloudErrorBody + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CloudErrorBody(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Target, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBodyTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CloudErrorBody(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Target, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBodyTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CloudErrorBody(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.HanaOnAzure.Models.Api20181130.ICloudErrorBody DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CloudErrorBody(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.HanaOnAzure.Models.Api20181130.ICloudErrorBody FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// An error response from the ManagedServiceIdentity service. + [System.ComponentModel.TypeConverter(typeof(CloudErrorBodyTypeConverter))] + public partial interface ICloudErrorBody + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.TypeConverter.cs new file mode 100644 index 000000000000..2afbcea2b797 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CloudErrorBodyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CloudErrorBody.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CloudErrorBody.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CloudErrorBody.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/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.cs new file mode 100644 index 000000000000..1884b4d6bcec --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// An error response from the ManagedServiceIdentity service. + public partial class CloudErrorBody : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBodyInternal + { + + /// Backing field for property. + private string _code; + + /// An identifier for the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Code { get => this._code; set => this._code = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[] _detail; + + /// A list of additional details about the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[] Detail { get => this._detail; set => this._detail = value; } + + /// Backing field for property. + private string _message; + + /// + /// A message describing the error, intended to be suitable for display in a user interface. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Message { get => this._message; set => this._message = value; } + + /// Backing field for property. + private string _target; + + /// + /// The target of the particular error. For example, the name of the property in error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Target { get => this._target; set => this._target = value; } + + /// Creates an new instance. + public CloudErrorBody() + { + + } + } + /// An error response from the ManagedServiceIdentity service. + public partial interface ICloudErrorBody : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// An identifier for the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"An identifier for the error.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// A list of additional details about the error. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of additional details about the error.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[] Detail { get; set; } + /// + /// A message describing the error, intended to be suitable for display in a user interface. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A message describing the error, intended to be suitable for display in a user interface.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + /// + /// The target of the particular error. For example, the name of the property in error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The target of the particular error. For example, the name of the property in error.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; set; } + + } + /// An error response from the ManagedServiceIdentity service. + internal partial interface ICloudErrorBodyInternal + + { + /// An identifier for the error. + string Code { get; set; } + /// A list of additional details about the error. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody[] Detail { get; set; } + /// + /// A message describing the error, intended to be suitable for display in a user interface. + /// + string Message { get; set; } + /// + /// The target of the particular error. For example, the name of the property in error. + /// + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.json.cs new file mode 100644 index 000000000000..be5d71cbcd33 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/CloudErrorBody.json.cs @@ -0,0 +1,115 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// An error response from the ManagedServiceIdentity service. + public partial class CloudErrorBody + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal CloudErrorBody(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.CloudErrorBody.FromJson(__u) )) ))() : null : Detail;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ICloudErrorBody FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new CloudErrorBody(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.PowerShell.cs new file mode 100644 index 000000000000..30b408482b04 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.PowerShell.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Describes an identity resource. + [System.ComponentModel.TypeConverter(typeof(IdentityTypeConverter))] + public partial class Identity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Identity(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.HanaOnAzure.Models.Api20181130.IIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Identity(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.HanaOnAzure.Models.Api20181130.IIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Identity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).TenantId, 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 Identity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal)this).TenantId, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Describes an identity resource. + [System.ComponentModel.TypeConverter(typeof(IdentityTypeConverter))] + public partial interface IIdentity + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.TypeConverter.cs new file mode 100644 index 000000000000..035b4cca4a02 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Identity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Identity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Identity.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/HanaOnAzure/generated/api/Models/Api20181130/Identity.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.cs new file mode 100644 index 000000000000..22614086edf2 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.cs @@ -0,0 +1,146 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes an identity resource. + public partial class Identity : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResource(); + + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string ClientId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).ClientId; } + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Type = value; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal.ClientId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).ClientId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).ClientId = value; } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal.PrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).PrincipalId = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties()); set { {_property = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityInternal.TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).TenantId = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Name; } + + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string PrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).PrincipalId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties _property; + + /// The properties associated with the identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties()); } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Tag = value; } + + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).TenantId; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public Identity() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Describes an identity resource. + public partial interface IIdentity : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the app associated with the identity. This is a random generated UUID by MSI.", + SerializedName = @"clientId", + PossibleTypes = new [] { typeof(string) })] + string ClientId { get; } + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the service principal object associated with the created identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the tenant which the identity belongs to.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + + } + /// Describes an identity resource. + internal partial interface IIdentityInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + string ClientId { get; set; } + /// The id of the service principal object associated with the created identity. + string PrincipalId { get; set; } + /// The properties associated with the identity. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties Property { get; set; } + /// The id of the tenant which the identity belongs to. + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.json.cs new file mode 100644 index 000000000000..eb854a219d7a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Identity.json.cs @@ -0,0 +1,106 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes an identity resource. + public partial class Identity + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Identity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Identity(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties.FromJson(__jsonProperties) : Property;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __trackedResource?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.PowerShell.cs new file mode 100644 index 000000000000..d1a575670382 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.PowerShell.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Describes an identity resource. + [System.ComponentModel.TypeConverter(typeof(IdentityUpdateTypeConverter))] + public partial class IdentityUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IdentityUpdate(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.HanaOnAzure.Models.Api20181130.IIdentityUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IdentityUpdate(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.HanaOnAzure.Models.Api20181130.IIdentityUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IdentityUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdateTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).TenantId, 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 IdentityUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdateTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal)this).TenantId, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Describes an identity resource. + [System.ComponentModel.TypeConverter(typeof(IdentityUpdateTypeConverter))] + public partial interface IIdentityUpdate + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.TypeConverter.cs new file mode 100644 index 000000000000..e68bfaaf9629 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IdentityUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IdentityUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IdentityUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IdentityUpdate.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/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.cs new file mode 100644 index 000000000000..4a0f90962632 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.cs @@ -0,0 +1,171 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes an identity resource. + public partial class IdentityUpdate : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource(); + + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string ClientId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).ClientId; } + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type = value; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal.ClientId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).ClientId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).ClientId = value; } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal.PrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).PrincipalId = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties()); set { {_property = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateInternal.TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).TenantId = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Name; } + + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string PrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).PrincipalId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties _property; + + /// The properties associated with the identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties()); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags _tag; + + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdateTags()); set => this._tag = value; } + + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)Property).TenantId; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__resource).Type; } + + /// Creates an new instance. + public IdentityUpdate() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// Describes an identity resource. + public partial interface IIdentityUpdate : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResource + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the app associated with the identity. This is a random generated UUID by MSI.", + SerializedName = @"clientId", + PossibleTypes = new [] { typeof(string) })] + string ClientId { get; } + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the service principal object associated with the created identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags Tag { get; set; } + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the tenant which the identity belongs to.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + + } + /// Describes an identity resource. + internal partial interface IIdentityUpdateInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + string ClientId { get; set; } + /// The geo-location where the resource lives + string Location { get; set; } + /// The id of the service principal object associated with the created identity. + string PrincipalId { get; set; } + /// The properties associated with the identity. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties Property { get; set; } + /// Resource tags + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags Tag { get; set; } + /// The id of the tenant which the identity belongs to. + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.json.cs new file mode 100644 index 000000000000..59e7f09a85bd --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdate.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes an identity resource. + public partial class IdentityUpdate + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new IdentityUpdate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal IdentityUpdate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.Resource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.UserAssignedIdentityProperties.FromJson(__jsonProperties) : Property;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdateTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + } + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.PowerShell.cs new file mode 100644 index 000000000000..fa26e6847834 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(IdentityUpdateTagsTypeConverter))] + public partial class IdentityUpdateTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new IdentityUpdateTags(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.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new IdentityUpdateTags(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.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal IdentityUpdateTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal IdentityUpdateTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(IdentityUpdateTagsTypeConverter))] + public partial interface IIdentityUpdateTags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.TypeConverter.cs new file mode 100644 index 000000000000..763455d95aa2 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IdentityUpdateTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return IdentityUpdateTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return IdentityUpdateTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return IdentityUpdateTags.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/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.cs new file mode 100644 index 000000000000..6f45e503ba5f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource tags + public partial class IdentityUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTagsInternal + { + + /// Creates an new instance. + public IdentityUpdateTags() + { + + } + } + /// Resource tags + public partial interface IIdentityUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// Resource tags + internal partial interface IIdentityUpdateTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.dictionary.cs new file mode 100644 index 000000000000..1dec43504003 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class IdentityUpdateTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdateTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.json.cs new file mode 100644 index 000000000000..c2ecdfccc7cd --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/IdentityUpdateTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource tags + public partial class IdentityUpdateTags + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new IdentityUpdateTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal IdentityUpdateTags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.PowerShell.cs new file mode 100644 index 000000000000..5068fc2919bb --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.PowerShell.cs @@ -0,0 +1,141 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Operation supported by the Microsoft.ManagedIdentity REST 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); + + /// + /// 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.HanaOnAzure.Models.Api20181130.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.HanaOnAzure.Models.Api20181130.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.HanaOnAzure.Models.Api20181130.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Operation supported by the Microsoft.ManagedIdentity REST API. + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.TypeConverter.cs new file mode 100644 index 000000000000..b0466d90433a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.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/HanaOnAzure/generated/api/Models/Api20181130/Operation.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.cs new file mode 100644 index 000000000000..af6656f956de --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.cs @@ -0,0 +1,120 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Operation supported by the Microsoft.ManagedIdentity REST API. + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay _display; + + /// The object that describes the operation. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationDisplay()); set => this._display = value; } + + /// A description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Description = value; } + + /// The type of operation. For example: read, write, delete. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Operation = value; } + + /// Friendly name of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Provider = value; } + + /// The resource type on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationDisplay()); set { {_display = value;} } } + + /// Backing field for property. + private string _name; + + /// + /// The name of the REST Operation. This is of the format {provider}/{resource}/{operation}. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// Operation supported by the Microsoft.ManagedIdentity REST API. + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// A description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A description of the operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; set; } + /// The type of operation. For example: read, write, delete. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The type of operation. For example: read, write, delete.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; set; } + /// Friendly name of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Friendly name of the resource provider.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; set; } + /// The resource type on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource type on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; set; } + /// + /// The name of the REST Operation. This is of the format {provider}/{resource}/{operation}. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the REST Operation. This is of the format {provider}/{resource}/{operation}.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Operation supported by the Microsoft.ManagedIdentity REST API. + internal partial interface IOperationInternal + + { + /// The object that describes the operation. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay Display { get; set; } + /// A description of the operation. + string DisplayDescription { get; set; } + /// The type of operation. For example: read, write, delete. + string DisplayOperation { get; set; } + /// Friendly name of the resource provider. + string DisplayProvider { get; set; } + /// The resource type on which the operation is performed. + string DisplayResource { get; set; } + /// + /// The name of the REST Operation. This is of the format {provider}/{resource}/{operation}. + /// + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.json.cs new file mode 100644 index 000000000000..f3202939338a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/Operation.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Operation supported by the Microsoft.ManagedIdentity REST 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Models.Api20181130.OperationDisplay.FromJson(__jsonDisplay) : Display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.PowerShell.cs new file mode 100644 index 000000000000..319ac61ef2be --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The object that describes the 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); + + /// + /// 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.HanaOnAzure.Models.Api20181130.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.HanaOnAzure.Models.Api20181130.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.HanaOnAzure.Models.Api20181130.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The object that describes the operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.TypeConverter.cs new file mode 100644 index 000000000000..600b2e7776a0 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.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/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.cs new file mode 100644 index 000000000000..6bca23aba946 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.cs @@ -0,0 +1,97 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The object that describes the operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// A description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _operation; + + /// The type of operation. For example: read, write, delete. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Operation { get => this._operation; set => this._operation = value; } + + /// Backing field for property. + private string _provider; + + /// Friendly name of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Provider { get => this._provider; set => this._provider = value; } + + /// Backing field for property. + private string _resource; + + /// The resource type on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Resource { get => this._resource; set => this._resource = value; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// The object that describes the operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// A description of the operation. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A description of the operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// The type of operation. For example: read, write, delete. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The type of operation. For example: read, write, delete.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; set; } + /// Friendly name of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Friendly name of the resource provider.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; set; } + /// The resource type on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource type on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; set; } + + } + /// The object that describes the operation. + internal partial interface IOperationDisplayInternal + + { + /// A description of the operation. + string Description { get; set; } + /// The type of operation. For example: read, write, delete. + string Operation { get; set; } + /// Friendly name of the resource provider. + string Provider { get; set; } + /// The resource type on which the operation is performed. + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.json.cs new file mode 100644 index 000000000000..be890ee77366 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationDisplay.json.cs @@ -0,0 +1,107 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The object that describes the 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)Description;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)Operation;} + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)Provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)Resource;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.PowerShell.cs new file mode 100644 index 000000000000..a28a280a826b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + [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); + + /// + /// 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.HanaOnAzure.Models.Api20181130.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.HanaOnAzure.Models.Api20181130.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.HanaOnAzure.Models.Api20181130.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationTypeConverter.ConvertFrom)); + 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 + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.OperationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial interface IOperationListResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.TypeConverter.cs new file mode 100644 index 000000000000..332f85a9550c --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.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/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.cs new file mode 100644 index 000000000000..796365883185 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + public partial class OperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The url to get the next page of results, if any. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation[] _value; + + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationListResult() + { + + } + } + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + public partial interface IOperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The url to get the next page of results, if any. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The url to get the next page of results, if any.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A list of operations supported by Microsoft.ManagedIdentity Resource Provider.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation[] Value { get; set; } + + } + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + internal partial interface IOperationListResultInternal + + { + /// The url to get the next page of results, if any. + string NextLink { get; set; } + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.json.cs new file mode 100644 index 000000000000..7f4616b7bdfb --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/OperationListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// A list of operations supported by Microsoft.ManagedIdentity Resource Provider. + 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Operation.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.PowerShell.cs new file mode 100644 index 000000000000..9ff118d1d1c8 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.PowerShell.cs @@ -0,0 +1,149 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Describes a system assigned identity resource. + [System.ComponentModel.TypeConverter(typeof(SystemAssignedIdentityTypeConverter))] + public partial class SystemAssignedIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemAssignedIdentity(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.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemAssignedIdentity(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.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemAssignedIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientSecretUrl = (string) content.GetValueForProperty("ClientSecretUrl",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientSecretUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).TenantId, 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 SystemAssignedIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientSecretUrl = (string) content.GetValueForProperty("ClientSecretUrl",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).ClientSecretUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal)this).TenantId, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Describes a system assigned identity resource. + [System.ComponentModel.TypeConverter(typeof(SystemAssignedIdentityTypeConverter))] + public partial interface ISystemAssignedIdentity + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.TypeConverter.cs new file mode 100644 index 000000000000..9f3884b6657b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemAssignedIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemAssignedIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemAssignedIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemAssignedIdentity.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/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.cs new file mode 100644 index 000000000000..f35bcaf754e0 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.cs @@ -0,0 +1,195 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes a system assigned identity resource. + public partial class SystemAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ProxyResource(); + + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string ClientId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).ClientId; } + + /// + /// The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string ClientSecretUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).ClientSecretUrl; } + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Type = value; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal.ClientId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).ClientId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).ClientId = value; } + + /// Internal Acessors for ClientSecretUrl + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal.ClientSecretUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).ClientSecretUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).ClientSecretUrl = value; } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal.PrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).PrincipalId = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityProperties()); set { {_property = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityInternal.TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).TenantId = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Name; } + + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string PrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).PrincipalId; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties _property; + + /// The properties associated with the identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityProperties()); } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags _tag; + + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityTags()); set => this._tag = value; } + + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string TenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)Property).TenantId; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public SystemAssignedIdentity() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Describes a system assigned identity resource. + public partial interface ISystemAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the app associated with the identity. This is a random generated UUID by MSI.", + SerializedName = @"clientId", + PossibleTypes = new [] { typeof(string) })] + string ClientId { get; } + /// + /// The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @" The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials.", + SerializedName = @"clientSecretUrl", + PossibleTypes = new [] { typeof(string) })] + string ClientSecretUrl { get; } + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the service principal object associated with the created identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags Tag { get; set; } + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the tenant which the identity belongs to.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + + } + /// Describes a system assigned identity resource. + internal partial interface ISystemAssignedIdentityInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResourceInternal + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + string ClientId { get; set; } + /// + /// The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials. + /// + string ClientSecretUrl { get; set; } + /// The geo-location where the resource lives + string Location { get; set; } + /// The id of the service principal object associated with the created identity. + string PrincipalId { get; set; } + /// The properties associated with the identity. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties Property { get; set; } + /// Resource tags + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags Tag { get; set; } + /// The id of the tenant which the identity belongs to. + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.json.cs new file mode 100644 index 000000000000..4d78bcd10a6a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentity.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes a system assigned identity resource. + public partial class SystemAssignedIdentity + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new SystemAssignedIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal SystemAssignedIdentity(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityProperties.FromJson(__jsonProperties) : Property;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __proxyResource?.ToJson(container, serializationMode); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + } + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.PowerShell.cs new file mode 100644 index 000000000000..3c07dec99883 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The properties associated with the system assigned identity. + [System.ComponentModel.TypeConverter(typeof(SystemAssignedIdentityPropertiesTypeConverter))] + public partial class SystemAssignedIdentityProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemAssignedIdentityProperties(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.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemAssignedIdentityProperties(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.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemAssignedIdentityProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientSecretUrl = (string) content.GetValueForProperty("ClientSecretUrl",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientSecretUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).TenantId, 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 SystemAssignedIdentityProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientSecretUrl = (string) content.GetValueForProperty("ClientSecretUrl",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).ClientSecretUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal)this).TenantId, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The properties associated with the system assigned identity. + [System.ComponentModel.TypeConverter(typeof(SystemAssignedIdentityPropertiesTypeConverter))] + public partial interface ISystemAssignedIdentityProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.TypeConverter.cs new file mode 100644 index 000000000000..081e102bdee7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemAssignedIdentityPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemAssignedIdentityProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemAssignedIdentityProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemAssignedIdentityProperties.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/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.cs new file mode 100644 index 000000000000..703ddf7917d5 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.cs @@ -0,0 +1,121 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The properties associated with the system assigned identity. + public partial class SystemAssignedIdentityProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal + { + + /// Backing field for property. + private string _clientId; + + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Backing field for property. + private string _clientSecretUrl; + + /// + /// The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ClientSecretUrl { get => this._clientSecretUrl; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for ClientSecretUrl + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal.ClientSecretUrl { get => this._clientSecretUrl; set { {_clientSecretUrl = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityPropertiesInternal.TenantId { get => this._tenantId; set { {_tenantId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Backing field for property. + private string _tenantId; + + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; } + + /// Creates an new instance. + public SystemAssignedIdentityProperties() + { + + } + } + /// The properties associated with the system assigned identity. + public partial interface ISystemAssignedIdentityProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the app associated with the identity. This is a random generated UUID by MSI.", + SerializedName = @"clientId", + PossibleTypes = new [] { typeof(string) })] + string ClientId { get; } + /// + /// The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @" The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials.", + SerializedName = @"clientSecretUrl", + PossibleTypes = new [] { typeof(string) })] + string ClientSecretUrl { get; } + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the service principal object associated with the created identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the tenant which the identity belongs to.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + + } + /// The properties associated with the system assigned identity. + internal partial interface ISystemAssignedIdentityPropertiesInternal + + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + string ClientId { get; set; } + /// + /// The ManagedServiceIdentity DataPlane URL that can be queried to obtain the identity credentials. + /// + string ClientSecretUrl { get; set; } + /// The id of the service principal object associated with the created identity. + string PrincipalId { get; set; } + /// The id of the tenant which the identity belongs to. + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.json.cs new file mode 100644 index 000000000000..2757cd594a0b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityProperties.json.cs @@ -0,0 +1,119 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The properties associated with the system assigned identity. + public partial class SystemAssignedIdentityProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new SystemAssignedIdentityProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal SystemAssignedIdentityProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_clientId = If( json?.PropertyT("clientId"), out var __jsonClientId) ? (string)__jsonClientId : (string)ClientId;} + {_clientSecretUrl = If( json?.PropertyT("clientSecretUrl"), out var __jsonClientSecretUrl) ? (string)__jsonClientSecretUrl : (string)ClientSecretUrl;} + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)PrincipalId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)TenantId;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._clientSecretUrl)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._clientSecretUrl.ToString()) : null, "clientSecretUrl" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.PowerShell.cs new file mode 100644 index 000000000000..751f4dbb93ec --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(SystemAssignedIdentityTagsTypeConverter))] + public partial class SystemAssignedIdentityTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemAssignedIdentityTags(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.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemAssignedIdentityTags(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.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemAssignedIdentityTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SystemAssignedIdentityTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(SystemAssignedIdentityTagsTypeConverter))] + public partial interface ISystemAssignedIdentityTags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.TypeConverter.cs new file mode 100644 index 000000000000..79decbc3594b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemAssignedIdentityTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemAssignedIdentityTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemAssignedIdentityTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemAssignedIdentityTags.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/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.cs new file mode 100644 index 000000000000..ff0a04942827 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource tags + public partial class SystemAssignedIdentityTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTagsInternal + { + + /// Creates an new instance. + public SystemAssignedIdentityTags() + { + + } + } + /// Resource tags + public partial interface ISystemAssignedIdentityTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// Resource tags + internal partial interface ISystemAssignedIdentityTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.dictionary.cs new file mode 100644 index 000000000000..313dd46a0db4 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class SystemAssignedIdentityTags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.SystemAssignedIdentityTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.json.cs new file mode 100644 index 000000000000..9ec7014f7e65 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/SystemAssignedIdentityTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Resource tags + public partial class SystemAssignedIdentityTags + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.ISystemAssignedIdentityTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new SystemAssignedIdentityTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal SystemAssignedIdentityTags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.PowerShell.cs new file mode 100644 index 000000000000..76c7b9a5acb7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Values returned by the List operation. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentitiesListResultTypeConverter))] + public partial class UserAssignedIdentitiesListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserAssignedIdentitiesListResult(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.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserAssignedIdentitiesListResult(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.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserAssignedIdentitiesListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal UserAssignedIdentitiesListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + } + /// Values returned by the List operation. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentitiesListResultTypeConverter))] + public partial interface IUserAssignedIdentitiesListResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.TypeConverter.cs new file mode 100644 index 000000000000..3997715e1788 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserAssignedIdentitiesListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserAssignedIdentitiesListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserAssignedIdentitiesListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserAssignedIdentitiesListResult.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/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.cs new file mode 100644 index 000000000000..9109dacba1fb --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Values returned by the List operation. + public partial class UserAssignedIdentitiesListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The url to get the next page of results, if any. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity[] _value; + + /// The collection of userAssignedIdentities returned by the listing operation. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public UserAssignedIdentitiesListResult() + { + + } + } + /// Values returned by the List operation. + public partial interface IUserAssignedIdentitiesListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The url to get the next page of results, if any. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The url to get the next page of results, if any.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The collection of userAssignedIdentities returned by the listing operation. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The collection of userAssignedIdentities returned by the listing operation.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity[] Value { get; set; } + + } + /// Values returned by the List operation. + internal partial interface IUserAssignedIdentitiesListResultInternal + + { + /// The url to get the next page of results, if any. + string NextLink { get; set; } + /// The collection of userAssignedIdentities returned by the listing operation. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.json.cs new file mode 100644 index 000000000000..f5ee3573b2bd --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentitiesListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Values returned by the List operation. + public partial class UserAssignedIdentitiesListResult + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentitiesListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new UserAssignedIdentitiesListResult(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentitiesListResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.PowerShell.cs new file mode 100644 index 000000000000..e3bb5fe78b17 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The properties associated with the user assigned identity. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentityPropertiesTypeConverter))] + public partial class UserAssignedIdentityProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserAssignedIdentityProperties(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.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserAssignedIdentityProperties(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.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserAssignedIdentityProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).TenantId, 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 UserAssignedIdentityProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).ClientId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).PrincipalId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal)this).TenantId, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + } + /// The properties associated with the user assigned identity. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentityPropertiesTypeConverter))] + public partial interface IUserAssignedIdentityProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.TypeConverter.cs new file mode 100644 index 000000000000..2eb215e51dad --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserAssignedIdentityPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserAssignedIdentityProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserAssignedIdentityProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserAssignedIdentityProperties.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/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.cs new file mode 100644 index 000000000000..1c1df0137484 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.cs @@ -0,0 +1,95 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The properties associated with the user assigned identity. + public partial class UserAssignedIdentityProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal + { + + /// Backing field for property. + private string _clientId; + + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityPropertiesInternal.TenantId { get => this._tenantId; set { {_tenantId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Backing field for property. + private string _tenantId; + + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; } + + /// Creates an new instance. + public UserAssignedIdentityProperties() + { + + } + } + /// The properties associated with the user assigned identity. + public partial interface IUserAssignedIdentityProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the app associated with the identity. This is a random generated UUID by MSI.", + SerializedName = @"clientId", + PossibleTypes = new [] { typeof(string) })] + string ClientId { get; } + /// The id of the service principal object associated with the created identity. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the service principal object associated with the created identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// The id of the tenant which the identity belongs to. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The id of the tenant which the identity belongs to.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + + } + /// The properties associated with the user assigned identity. + internal partial interface IUserAssignedIdentityPropertiesInternal + + { + /// + /// The id of the app associated with the identity. This is a random generated UUID by MSI. + /// + string ClientId { get; set; } + /// The id of the service principal object associated with the created identity. + string PrincipalId { get; set; } + /// The id of the tenant which the identity belongs to. + string TenantId { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.json.cs new file mode 100644 index 000000000000..bf8223298af7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20181130/UserAssignedIdentityProperties.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130 +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The properties associated with the user assigned identity. + public partial class UserAssignedIdentityProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IUserAssignedIdentityProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new UserAssignedIdentityProperties(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentityProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_clientId = If( json?.PropertyT("clientId"), out var __jsonClientId) ? (string)__jsonClientId : (string)ClientId;} + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)PrincipalId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)TenantId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.PowerShell.cs new file mode 100644 index 000000000000..393ea1fa4b83 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Detailed HANA operation information + [System.ComponentModel.TypeConverter(typeof(DisplayTypeConverter))] + public partial class Display + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Display(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.HanaOnAzure.Models.Api20200207Preview.IDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Display(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Display(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Origin, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Display(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Origin, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Detailed HANA operation information + [System.ComponentModel.TypeConverter(typeof(DisplayTypeConverter))] + public partial interface IDisplay + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.TypeConverter.cs new file mode 100644 index 000000000000..4b1e612ccca0 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class DisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Display.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Display.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Display.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/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.cs new file mode 100644 index 000000000000..b7cd40048a4f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.cs @@ -0,0 +1,174 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Detailed HANA operation information + public partial class Display : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// + /// The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. + /// It will be used in tool-tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal.Origin { get => this._origin; set { {_origin = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal.Resource { get => this._resource; set { {_resource = value;} } } + + /// Backing field for property. + private string _operation; + + /// + /// The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), + /// but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Operation { get => this._operation; } + + /// Backing field for property. + private string _origin; + + /// + /// The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default + /// value is 'user,system' + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Origin { get => this._origin; } + + /// Backing field for property. + private string _provider; + + /// + /// The localized friendly form of the resource provider name. This form is also expected to include the publisher/company + /// responsible. Use Title Casing. Begin with "Microsoft" for 1st party services. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Provider { get => this._provider; } + + /// Backing field for property. + private string _resource; + + /// + /// The localized friendly form of the resource type related to this action/operation. This form should match the public documentation + /// for the resource provider. Use Title Casing. For examples, refer to the “name” section. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Resource { get => this._resource; } + + /// Creates an new instance. + public Display() + { + + } + } + /// Detailed HANA operation information + public partial interface IDisplay : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. + /// It will be used in tool-tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. It will be used in tool-tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// + /// The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), + /// but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; } + /// + /// The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default + /// value is 'user,system' + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default value is 'user,system'", + SerializedName = @"origin", + PossibleTypes = new [] { typeof(string) })] + string Origin { get; } + /// + /// The localized friendly form of the resource provider name. This form is also expected to include the publisher/company + /// responsible. Use Title Casing. Begin with "Microsoft" for 1st party services. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly form of the resource provider name. This form is also expected to include the publisher/company responsible. Use Title Casing. Begin with ""Microsoft"" for 1st party services.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; } + /// + /// The localized friendly form of the resource type related to this action/operation. This form should match the public documentation + /// for the resource provider. Use Title Casing. For examples, refer to the “name” section. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly form of the resource type related to this action/operation. This form should match the public documentation for the resource provider. Use Title Casing. For examples, refer to the “name” section.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; } + + } + /// Detailed HANA operation information + internal partial interface IDisplayInternal + + { + /// + /// The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. + /// It will be used in tool-tips and detailed views. + /// + string Description { get; set; } + /// + /// The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), + /// but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies. + /// + string Operation { get; set; } + /// + /// The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default + /// value is 'user,system' + /// + string Origin { get; set; } + /// + /// The localized friendly form of the resource provider name. This form is also expected to include the publisher/company + /// responsible. Use Title Casing. Begin with "Microsoft" for 1st party services. + /// + string Provider { get; set; } + /// + /// The localized friendly form of the resource type related to this action/operation. This form should match the public documentation + /// for the resource provider. Use Title Casing. For examples, refer to the “name” section. + /// + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.json.cs new file mode 100644 index 000000000000..db2cac51ebca --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Display.json.cs @@ -0,0 +1,124 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Detailed HANA operation information + public partial class Display + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Display(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)Description;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)Operation;} + {_origin = If( json?.PropertyT("origin"), out var __jsonOrigin) ? (string)__jsonOrigin : (string)Origin;} + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)Provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)Resource;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Display(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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.PowerShell.cs new file mode 100644 index 000000000000..a6e91f3f1082 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Describes the format of Error response. + [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); + + /// + /// 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.HanaOnAzure.Models.Api20200207Preview.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.HanaOnAzure.Models.Api20200207Preview.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 + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Describes the format of Error response. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.TypeConverter.cs new file mode 100644 index 000000000000..d78f81d2bf86 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.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/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.cs new file mode 100644 index 000000000000..f32b29adba2d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes the format of Error response. + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponseInternal + { + + /// Backing field for property. + private string _code; + + /// Error code + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Code { get => this._code; set => this._code = value; } + + /// Backing field for property. + private string _message; + + /// Error message indicating why the operation failed. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Message { get => this._message; set => this._message = value; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Describes the format of Error response. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// Error code + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Error code", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// Error message indicating why the operation failed. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Error message indicating why the operation failed.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + + } + /// Describes the format of Error response. + internal partial interface IErrorResponseInternal + + { + /// Error code + string Code { get; set; } + /// Error message indicating why the operation failed. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.json.cs new file mode 100644 index 000000000000..ad905f2fae1a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ErrorResponse.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes the format of Error response. + 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_code = If( json?.PropertyT("code"), out var __jsonCode) ? (string)__jsonCode : (string)Code;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.PowerShell.cs new file mode 100644 index 000000000000..eab58bc98737 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.PowerShell.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// HANA operation information + [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); + + /// + /// 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.HanaOnAzure.Models.Api20200207Preview.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.HanaOnAzure.Models.Api20200207Preview.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.HanaOnAzure.Models.Api20200207Preview.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.DisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOrigin = (string) content.GetValueForProperty("DisplayOrigin",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOrigin, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.DisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOrigin = (string) content.GetValueForProperty("DisplayOrigin",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayOrigin, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// HANA operation information + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.TypeConverter.cs new file mode 100644 index 000000000000..a9e7c4e5dffe --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.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/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.cs new file mode 100644 index 000000000000..11c2796bed6b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.cs @@ -0,0 +1,200 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// HANA operation information + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay _display; + + /// Displayed HANA operation information + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Display()); set => this._display = value; } + + /// + /// The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. + /// It will be used in tool-tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Description; } + + /// + /// The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), + /// but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Operation; } + + /// + /// The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default + /// value is 'user,system' + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayOrigin { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Origin; } + + /// + /// The localized friendly form of the resource provider name. This form is also expected to include the publisher/company + /// responsible. Use Title Casing. Begin with "Microsoft" for 1st party services. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Provider; } + + /// + /// The localized friendly form of the resource type related to this action/operation. This form should match the public documentation + /// for the resource provider. Use Title Casing. For examples, refer to the “name” section. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Resource; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Display()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Description = value; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Operation = value; } + + /// Internal Acessors for DisplayOrigin + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal.DisplayOrigin { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Origin; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Origin = value; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Provider = value; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Backing field for property. + private string _name; + + /// + /// The name of the operation being performed on this particular object. This name should match the action name that appears + /// in RBAC / the event service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// HANA operation information + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// + /// The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. + /// It will be used in tool-tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. It will be used in tool-tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; } + /// + /// The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), + /// but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; } + /// + /// The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default + /// value is 'user,system' + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default value is 'user,system'", + SerializedName = @"origin", + PossibleTypes = new [] { typeof(string) })] + string DisplayOrigin { get; } + /// + /// The localized friendly form of the resource provider name. This form is also expected to include the publisher/company + /// responsible. Use Title Casing. Begin with "Microsoft" for 1st party services. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly form of the resource provider name. This form is also expected to include the publisher/company responsible. Use Title Casing. Begin with ""Microsoft"" for 1st party services.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; } + /// + /// The localized friendly form of the resource type related to this action/operation. This form should match the public documentation + /// for the resource provider. Use Title Casing. For examples, refer to the “name” section. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The localized friendly form of the resource type related to this action/operation. This form should match the public documentation for the resource provider. Use Title Casing. For examples, refer to the “name” section.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; } + /// + /// The name of the operation being performed on this particular object. This name should match the action name that appears + /// in RBAC / the event service. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the operation being performed on this particular object. This name should match the action name that appears in RBAC / the event service.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + + } + /// HANA operation information + internal partial interface IOperationInternal + + { + /// Displayed HANA operation information + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IDisplay Display { get; set; } + /// + /// The localized friendly description for the operation as shown to the user. This description should be thorough, yet concise. + /// It will be used in tool-tips and detailed views. + /// + string DisplayDescription { get; set; } + /// + /// The localized friendly name for the operation as shown to the user. This name should be concise (to fit in drop downs), + /// but clear (self-documenting). Use Title Casing and include the entity/resource to which it applies. + /// + string DisplayOperation { get; set; } + /// + /// The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default + /// value is 'user,system' + /// + string DisplayOrigin { get; set; } + /// + /// The localized friendly form of the resource provider name. This form is also expected to include the publisher/company + /// responsible. Use Title Casing. Begin with "Microsoft" for 1st party services. + /// + string DisplayProvider { get; set; } + /// + /// The localized friendly form of the resource type related to this action/operation. This form should match the public documentation + /// for the resource provider. Use Title Casing. For examples, refer to the “name” section. + /// + string DisplayResource { get; set; } + /// + /// The name of the operation being performed on this particular object. This name should match the action name that appears + /// in RBAC / the event service. + /// + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.json.cs new file mode 100644 index 000000000000..ad49dc37b247 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Operation.json.cs @@ -0,0 +1,106 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// HANA operation information + 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Models.Api20200207Preview.Display.FromJson(__jsonDisplay) : Display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.PowerShell.cs new file mode 100644 index 000000000000..5f921273220e --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.PowerShell.cs @@ -0,0 +1,131 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// List of HANA operations + [System.ComponentModel.TypeConverter(typeof(OperationListTypeConverter))] + public partial class OperationList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationList(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.HanaOnAzure.Models.Api20200207Preview.IOperationList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationList(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.HanaOnAzure.Models.Api20200207Preview.IOperationList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.OperationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.OperationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// List of HANA operations + [System.ComponentModel.TypeConverter(typeof(OperationListTypeConverter))] + public partial interface IOperationList + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.TypeConverter.cs new file mode 100644 index 000000000000..b043bdbf7172 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationList.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/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.cs new file mode 100644 index 000000000000..bb57b17edf2c --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of HANA operations + public partial class OperationList : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationList, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationListInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation[] _value; + + /// List of HANA operations + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationList() + { + + } + } + /// List of HANA operations + public partial interface IOperationList : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// List of HANA operations + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of HANA operations", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation[] Value { get; set; } + + } + /// List of HANA operations + internal partial interface IOperationListInternal + + { + /// List of HANA operations + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.json.cs new file mode 100644 index 000000000000..40b8af92884a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/OperationList.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// List of HANA operations + public partial class OperationList + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperationList FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new OperationList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal OperationList(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Operation.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.PowerShell.cs new file mode 100644 index 000000000000..e47b18c2ad77 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.PowerShell.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// A provider instance associated with a SAP monitor. + [System.ComponentModel.TypeConverter(typeof(ProviderInstanceTypeConverter))] + public partial class ProviderInstance + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProviderInstance(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.HanaOnAzure.Models.Api20200207Preview.IProviderInstance DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProviderInstance(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.HanaOnAzure.Models.Api20200207Preview.IProviderInstance FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProviderInstance(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstancePropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProviderInstanceProperty = (string) content.GetValueForProperty("ProviderInstanceProperty",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProviderInstanceProperty, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).PropertiesType = (string) content.GetValueForProperty("PropertiesType",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).PropertiesType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Metadata = (string) content.GetValueForProperty("Metadata",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Metadata, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ProviderInstance(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstancePropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProviderInstanceProperty = (string) content.GetValueForProperty("ProviderInstanceProperty",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProviderInstanceProperty, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).PropertiesType = (string) content.GetValueForProperty("PropertiesType",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).PropertiesType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Metadata = (string) content.GetValueForProperty("Metadata",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).Metadata, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// A provider instance associated with a SAP monitor. + [System.ComponentModel.TypeConverter(typeof(ProviderInstanceTypeConverter))] + public partial interface IProviderInstance + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.TypeConverter.cs new file mode 100644 index 000000000000..f495d1cdc50a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProviderInstanceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProviderInstance.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProviderInstance.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProviderInstance.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/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.cs new file mode 100644 index 000000000000..f294d4fedd19 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.cs @@ -0,0 +1,148 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// A provider instance associated with a SAP monitor. + public partial class ProviderInstance : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ProxyResource(); + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Id; } + + /// A JSON string containing metadata of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string Metadata { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).Metadata; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).Metadata = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Type = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).ProvisioningState = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.FormatTable(Index = 0)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Name; } + + /// The type of provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string PropertiesType { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).Type = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties _property; + + /// Provider Instance properties + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceProperties()); set => this._property = value; } + + /// A JSON string containing the properties of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string ProviderInstanceProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).Property; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).Property = value; } + + /// State of provisioning of the provider instance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)Property).ProvisioningState; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public ProviderInstance() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// A provider instance associated with a SAP monitor. + public partial interface IProviderInstance : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResource + { + /// A JSON string containing metadata of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A JSON string containing metadata of the provider instance.", + SerializedName = @"metadata", + PossibleTypes = new [] { typeof(string) })] + string Metadata { get; set; } + /// The type of provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The type of provider instance.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string PropertiesType { get; set; } + /// A JSON string containing the properties of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A JSON string containing the properties of the provider instance.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(string) })] + string ProviderInstanceProperty { get; set; } + /// State of provisioning of the provider instance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"State of provisioning of the provider instance", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; } + + } + /// A provider instance associated with a SAP monitor. + internal partial interface IProviderInstanceInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IProxyResourceInternal + { + /// A JSON string containing metadata of the provider instance. + string Metadata { get; set; } + /// The type of provider instance. + string PropertiesType { get; set; } + /// Provider Instance properties + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties Property { get; set; } + /// A JSON string containing the properties of the provider instance. + string ProviderInstanceProperty { get; set; } + /// State of provisioning of the provider instance + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.json.cs new file mode 100644 index 000000000000..e8114b3dc070 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstance.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// A provider instance associated with a SAP monitor. + public partial class ProviderInstance + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new ProviderInstance(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal ProviderInstance(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceProperties.FromJson(__jsonProperties) : Property;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.PowerShell.cs new file mode 100644 index 000000000000..31c3173ef162 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The response from the List provider instances operation. + [System.ComponentModel.TypeConverter(typeof(ProviderInstanceListResultTypeConverter))] + public partial class ProviderInstanceListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProviderInstanceListResult(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.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProviderInstanceListResult(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.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProviderInstanceListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ProviderInstanceListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstanceTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The response from the List provider instances operation. + [System.ComponentModel.TypeConverter(typeof(ProviderInstanceListResultTypeConverter))] + public partial interface IProviderInstanceListResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.TypeConverter.cs new file mode 100644 index 000000000000..bbf67d83e974 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProviderInstanceListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProviderInstanceListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProviderInstanceListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProviderInstanceListResult.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/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.cs new file mode 100644 index 000000000000..e77cfd55b9ee --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The response from the List provider instances operation. + public partial class ProviderInstanceListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to get the next set of provider instances. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance[] _value; + + /// The list of provider instances. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ProviderInstanceListResult() + { + + } + } + /// The response from the List provider instances operation. + public partial interface IProviderInstanceListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The URL to get the next set of provider instances. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to get the next set of provider instances.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of provider instances. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of provider instances.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance[] Value { get; set; } + + } + /// The response from the List provider instances operation. + internal partial interface IProviderInstanceListResultInternal + + { + /// The URL to get the next set of provider instances. + string NextLink { get; set; } + /// The list of provider instances. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.json.cs new file mode 100644 index 000000000000..1ed738cde44c --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The response from the List provider instances operation. + public partial class ProviderInstanceListResult + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new ProviderInstanceListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal ProviderInstanceListResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstance.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.PowerShell.cs new file mode 100644 index 000000000000..e5e3278ae8e7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Describes the properties of a provider instance. + [System.ComponentModel.TypeConverter(typeof(ProviderInstancePropertiesTypeConverter))] + public partial class ProviderInstanceProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProviderInstanceProperties(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.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProviderInstanceProperties(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.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProviderInstanceProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Metadata = (string) content.GetValueForProperty("Metadata",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Metadata, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Property = (string) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Property, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ProviderInstanceProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Metadata = (string) content.GetValueForProperty("Metadata",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Metadata, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Property = (string) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).Property, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Describes the properties of a provider instance. + [System.ComponentModel.TypeConverter(typeof(ProviderInstancePropertiesTypeConverter))] + public partial interface IProviderInstanceProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.TypeConverter.cs new file mode 100644 index 000000000000..1fcfb2b576a1 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProviderInstancePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProviderInstanceProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProviderInstanceProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProviderInstanceProperties.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/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.cs new file mode 100644 index 000000000000..ff0c1bddcbe7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.cs @@ -0,0 +1,100 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes the properties of a provider instance. + public partial class ProviderInstanceProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal + { + + /// Backing field for property. + private string _metadata; + + /// A JSON string containing metadata of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Metadata { get => this._metadata; set => this._metadata = value; } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstancePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _property; + + /// A JSON string containing the properties of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Property { get => this._property; set => this._property = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? _provisioningState; + + /// State of provisioning of the provider instance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _type; + + /// The type of provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Creates an new instance. + public ProviderInstanceProperties() + { + + } + } + /// Describes the properties of a provider instance. + public partial interface IProviderInstanceProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// A JSON string containing metadata of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A JSON string containing metadata of the provider instance.", + SerializedName = @"metadata", + PossibleTypes = new [] { typeof(string) })] + string Metadata { get; set; } + /// A JSON string containing the properties of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A JSON string containing the properties of the provider instance.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(string) })] + string Property { get; set; } + /// State of provisioning of the provider instance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"State of provisioning of the provider instance", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; } + /// The type of provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The type of provider instance.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; set; } + + } + /// Describes the properties of a provider instance. + internal partial interface IProviderInstancePropertiesInternal + + { + /// A JSON string containing metadata of the provider instance. + string Metadata { get; set; } + /// A JSON string containing the properties of the provider instance. + string Property { get; set; } + /// State of provisioning of the provider instance + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; set; } + /// The type of provider instance. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.json.cs new file mode 100644 index 000000000000..6de6c16f0dbf --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/ProviderInstanceProperties.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes the properties of a provider instance. + public partial class ProviderInstanceProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstanceProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new ProviderInstanceProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal ProviderInstanceProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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;} + {_metadata = If( json?.PropertyT("metadata"), out var __jsonMetadata) ? (string)__jsonMetadata : (string)Metadata;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? (string)__jsonProperties : (string)Property;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != (((object)this._metadata)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._metadata.ToString()) : null, "metadata" ,container.Add ); + AddIf( null != (((object)this._property)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._property.ToString()) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.PowerShell.cs new file mode 100644 index 000000000000..935af28ee919 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.PowerShell.cs @@ -0,0 +1,157 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// SAP monitor info on Azure (ARM properties and SAP monitor properties) + [System.ComponentModel.TypeConverter(typeof(SapMonitorTypeConverter))] + public partial class SapMonitor + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SapMonitor(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.HanaOnAzure.Models.Api20200207Preview.ISapMonitor DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SapMonitor(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.HanaOnAzure.Models.Api20200207Preview.ISapMonitor FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SapMonitor(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).EnableCustomerAnalytic = (bool?) content.GetValueForProperty("EnableCustomerAnalytic",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).EnableCustomerAnalytic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceArmId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceArmId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceArmId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceSharedKey = (string) content.GetValueForProperty("LogAnalyticsWorkspaceSharedKey",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceSharedKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ManagedResourceGroupName = (string) content.GetValueForProperty("ManagedResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ManagedResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).MonitorSubnet = (string) content.GetValueForProperty("MonitorSubnet",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).MonitorSubnet, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).CollectorVersion = (string) content.GetValueForProperty("CollectorVersion",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).CollectorVersion, 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 SapMonitor(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResourceTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).EnableCustomerAnalytic = (bool?) content.GetValueForProperty("EnableCustomerAnalytic",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).EnableCustomerAnalytic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceArmId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceArmId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceArmId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceSharedKey = (string) content.GetValueForProperty("LogAnalyticsWorkspaceSharedKey",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).LogAnalyticsWorkspaceSharedKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ManagedResourceGroupName = (string) content.GetValueForProperty("ManagedResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ManagedResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).MonitorSubnet = (string) content.GetValueForProperty("MonitorSubnet",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).MonitorSubnet, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).CollectorVersion = (string) content.GetValueForProperty("CollectorVersion",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal)this).CollectorVersion, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// SAP monitor info on Azure (ARM properties and SAP monitor properties) + [System.ComponentModel.TypeConverter(typeof(SapMonitorTypeConverter))] + public partial interface ISapMonitor + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.TypeConverter.cs new file mode 100644 index 000000000000..4000ebf8bda7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SapMonitorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SapMonitor.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SapMonitor.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SapMonitor.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/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.cs new file mode 100644 index 000000000000..46ef2c22e797 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.cs @@ -0,0 +1,224 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// SAP monitor info on Azure (ARM properties and SAP monitor properties) + public partial class SapMonitor : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResource(); + + /// The version of the payload running in the Collector VM + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string CollectorVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).SapMonitorCollectorVersion; } + + /// The value indicating whether to send analytics to Microsoft + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public bool? EnableCustomerAnalytic { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).EnableCustomerAnalytic; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).EnableCustomerAnalytic = value; } + + /// The Azure Resource Manager resource ID for the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.FormatTable(Index = 1)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Location = value; } + + /// The ARM ID of the Log Analytics Workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string LogAnalyticsWorkspaceArmId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).LogAnalyticsWorkspaceArmId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).LogAnalyticsWorkspaceArmId = value; } + + /// The workspace ID of the log analytics workspace to be used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string LogAnalyticsWorkspaceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).LogAnalyticsWorkspaceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).LogAnalyticsWorkspaceId = value; } + + /// The shared key of the log analytics workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string LogAnalyticsWorkspaceSharedKey { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).LogAnalyticsWorkspaceSharedKey; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).LogAnalyticsWorkspaceSharedKey = value; } + + /// The name of the resource group the SAP Monitor resources get deployed into. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string ManagedResourceGroupName { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).ManagedResourceGroupName; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Type = value; } + + /// Internal Acessors for CollectorVersion + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal.CollectorVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).SapMonitorCollectorVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).SapMonitorCollectorVersion = value; } + + /// Internal Acessors for ManagedResourceGroupName + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal.ManagedResourceGroupName { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).ManagedResourceGroupName; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).ManagedResourceGroupName = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).ProvisioningState = value; } + + /// The subnet which the SAP monitor will be deployed in + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string MonitorSubnet { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).MonitorSubnet; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).MonitorSubnet = value; } + + /// The name of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.FormatTable(Index = 0)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties _property; + + /// SAP monitor properties + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + internal Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorProperties()); set => this._property = value; } + + /// State of provisioning of the HanaInstance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)Property).ProvisioningState; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal)__trackedResource).Tag = value; } + + /// The resource type of the key vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Inherited)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.DoNotFormat] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public SapMonitor() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// SAP monitor info on Azure (ARM properties and SAP monitor properties) + public partial interface ISapMonitor : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResource + { + /// The version of the payload running in the Collector VM + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The version of the payload running in the Collector VM", + SerializedName = @"sapMonitorCollectorVersion", + PossibleTypes = new [] { typeof(string) })] + string CollectorVersion { get; } + /// The value indicating whether to send analytics to Microsoft + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The value indicating whether to send analytics to Microsoft", + SerializedName = @"enableCustomerAnalytics", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableCustomerAnalytic { get; set; } + /// The ARM ID of the Log Analytics Workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM ID of the Log Analytics Workspace that is used for monitoring", + SerializedName = @"logAnalyticsWorkspaceArmId", + PossibleTypes = new [] { typeof(string) })] + string LogAnalyticsWorkspaceArmId { get; set; } + /// The workspace ID of the log analytics workspace to be used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The workspace ID of the log analytics workspace to be used for monitoring", + SerializedName = @"logAnalyticsWorkspaceId", + PossibleTypes = new [] { typeof(string) })] + string LogAnalyticsWorkspaceId { get; set; } + /// The shared key of the log analytics workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The shared key of the log analytics workspace that is used for monitoring", + SerializedName = @"logAnalyticsWorkspaceSharedKey", + PossibleTypes = new [] { typeof(string) })] + string LogAnalyticsWorkspaceSharedKey { get; set; } + /// The name of the resource group the SAP Monitor resources get deployed into. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the resource group the SAP Monitor resources get deployed into.", + SerializedName = @"managedResourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ManagedResourceGroupName { get; } + /// The subnet which the SAP monitor will be deployed in + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The subnet which the SAP monitor will be deployed in", + SerializedName = @"monitorSubnet", + PossibleTypes = new [] { typeof(string) })] + string MonitorSubnet { get; set; } + /// State of provisioning of the HanaInstance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"State of provisioning of the HanaInstance", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; } + + } + /// SAP monitor info on Azure (ARM properties and SAP monitor properties) + internal partial interface ISapMonitorInternal : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceInternal + { + /// The version of the payload running in the Collector VM + string CollectorVersion { get; set; } + /// The value indicating whether to send analytics to Microsoft + bool? EnableCustomerAnalytic { get; set; } + /// The ARM ID of the Log Analytics Workspace that is used for monitoring + string LogAnalyticsWorkspaceArmId { get; set; } + /// The workspace ID of the log analytics workspace to be used for monitoring + string LogAnalyticsWorkspaceId { get; set; } + /// The shared key of the log analytics workspace that is used for monitoring + string LogAnalyticsWorkspaceSharedKey { get; set; } + /// The name of the resource group the SAP Monitor resources get deployed into. + string ManagedResourceGroupName { get; set; } + /// The subnet which the SAP monitor will be deployed in + string MonitorSubnet { get; set; } + /// SAP monitor properties + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties Property { get; set; } + /// State of provisioning of the HanaInstance + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.json.cs new file mode 100644 index 000000000000..d6e2149f3031 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitor.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// SAP monitor info on Azure (ARM properties and SAP monitor properties) + public partial class SapMonitor + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new SapMonitor(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal SapMonitor(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorProperties.FromJson(__jsonProperties) : Property;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __trackedResource?.ToJson(container, serializationMode); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.PowerShell.cs new file mode 100644 index 000000000000..122c09b54843 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// The response from the List SAP monitors operation. + [System.ComponentModel.TypeConverter(typeof(SapMonitorListResultTypeConverter))] + public partial class SapMonitorListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SapMonitorListResult(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.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SapMonitorListResult(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.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SapMonitorListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SapMonitorListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitorTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The response from the List SAP monitors operation. + [System.ComponentModel.TypeConverter(typeof(SapMonitorListResultTypeConverter))] + public partial interface ISapMonitorListResult + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.TypeConverter.cs new file mode 100644 index 000000000000..e814a327d2be --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SapMonitorListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SapMonitorListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SapMonitorListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SapMonitorListResult.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/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.cs new file mode 100644 index 000000000000..af8fe507ee15 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The response from the List SAP monitors operation. + public partial class SapMonitorListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The URL to get the next set of SAP monitors. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor[] _value; + + /// The list of SAP monitors. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public SapMonitorListResult() + { + + } + } + /// The response from the List SAP monitors operation. + public partial interface ISapMonitorListResult : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The URL to get the next set of SAP monitors. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The URL to get the next set of SAP monitors.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of SAP monitors. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The list of SAP monitors.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor[] Value { get; set; } + + } + /// The response from the List SAP monitors operation. + internal partial interface ISapMonitorListResultInternal + + { + /// The URL to get the next set of SAP monitors. + string NextLink { get; set; } + /// The list of SAP monitors. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.json.cs new file mode 100644 index 000000000000..8c8bd71979c0 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorListResult.json.cs @@ -0,0 +1,111 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// The response from the List SAP monitors operation. + public partial class SapMonitorListResult + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new SapMonitorListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal SapMonitorListResult(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor) (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitor.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.PowerShell.cs new file mode 100644 index 000000000000..2cbefa13f9e7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.PowerShell.cs @@ -0,0 +1,147 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Describes the properties of a SAP monitor. + [System.ComponentModel.TypeConverter(typeof(SapMonitorPropertiesTypeConverter))] + public partial class SapMonitorProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SapMonitorProperties(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.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SapMonitorProperties(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.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SapMonitorProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).EnableCustomerAnalytic = (bool?) content.GetValueForProperty("EnableCustomerAnalytic",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).EnableCustomerAnalytic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceArmId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceArmId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceArmId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceSharedKey = (string) content.GetValueForProperty("LogAnalyticsWorkspaceSharedKey",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceSharedKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ManagedResourceGroupName = (string) content.GetValueForProperty("ManagedResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ManagedResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).MonitorSubnet = (string) content.GetValueForProperty("MonitorSubnet",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).MonitorSubnet, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).SapMonitorCollectorVersion = (string) content.GetValueForProperty("SapMonitorCollectorVersion",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).SapMonitorCollectorVersion, 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 SapMonitorProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).EnableCustomerAnalytic = (bool?) content.GetValueForProperty("EnableCustomerAnalytic",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).EnableCustomerAnalytic, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceArmId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceArmId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceArmId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceId = (string) content.GetValueForProperty("LogAnalyticsWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceSharedKey = (string) content.GetValueForProperty("LogAnalyticsWorkspaceSharedKey",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).LogAnalyticsWorkspaceSharedKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ManagedResourceGroupName = (string) content.GetValueForProperty("ManagedResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ManagedResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).MonitorSubnet = (string) content.GetValueForProperty("MonitorSubnet",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).MonitorSubnet, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).SapMonitorCollectorVersion = (string) content.GetValueForProperty("SapMonitorCollectorVersion",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal)this).SapMonitorCollectorVersion, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Describes the properties of a SAP monitor. + [System.ComponentModel.TypeConverter(typeof(SapMonitorPropertiesTypeConverter))] + public partial interface ISapMonitorProperties + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.TypeConverter.cs new file mode 100644 index 000000000000..32e20582b06d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SapMonitorPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SapMonitorProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SapMonitorProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SapMonitorProperties.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/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.cs new file mode 100644 index 000000000000..01977af2649e --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.cs @@ -0,0 +1,174 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes the properties of a SAP monitor. + public partial class SapMonitorProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal + { + + /// Backing field for property. + private bool? _enableCustomerAnalytic; + + /// The value indicating whether to send analytics to Microsoft + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public bool? EnableCustomerAnalytic { get => this._enableCustomerAnalytic; set => this._enableCustomerAnalytic = value; } + + /// Backing field for property. + private string _logAnalyticsWorkspaceArmId; + + /// The ARM ID of the Log Analytics Workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string LogAnalyticsWorkspaceArmId { get => this._logAnalyticsWorkspaceArmId; set => this._logAnalyticsWorkspaceArmId = value; } + + /// Backing field for property. + private string _logAnalyticsWorkspaceId; + + /// The workspace ID of the log analytics workspace to be used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string LogAnalyticsWorkspaceId { get => this._logAnalyticsWorkspaceId; set => this._logAnalyticsWorkspaceId = value; } + + /// Backing field for property. + private string _logAnalyticsWorkspaceSharedKey; + + /// The shared key of the log analytics workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string LogAnalyticsWorkspaceSharedKey { get => this._logAnalyticsWorkspaceSharedKey; set => this._logAnalyticsWorkspaceSharedKey = value; } + + /// Backing field for property. + private string _managedResourceGroupName; + + /// The name of the resource group the SAP Monitor resources get deployed into. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ManagedResourceGroupName { get => this._managedResourceGroupName; } + + /// Internal Acessors for ManagedResourceGroupName + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal.ManagedResourceGroupName { get => this._managedResourceGroupName; set { {_managedResourceGroupName = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for SapMonitorCollectorVersion + string Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorPropertiesInternal.SapMonitorCollectorVersion { get => this._sapMonitorCollectorVersion; set { {_sapMonitorCollectorVersion = value;} } } + + /// Backing field for property. + private string _monitorSubnet; + + /// The subnet which the SAP monitor will be deployed in + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string MonitorSubnet { get => this._monitorSubnet; set => this._monitorSubnet = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? _provisioningState; + + /// State of provisioning of the HanaInstance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _sapMonitorCollectorVersion; + + /// The version of the payload running in the Collector VM + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string SapMonitorCollectorVersion { get => this._sapMonitorCollectorVersion; } + + /// Creates an new instance. + public SapMonitorProperties() + { + + } + } + /// Describes the properties of a SAP monitor. + public partial interface ISapMonitorProperties : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// The value indicating whether to send analytics to Microsoft + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The value indicating whether to send analytics to Microsoft", + SerializedName = @"enableCustomerAnalytics", + PossibleTypes = new [] { typeof(bool) })] + bool? EnableCustomerAnalytic { get; set; } + /// The ARM ID of the Log Analytics Workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM ID of the Log Analytics Workspace that is used for monitoring", + SerializedName = @"logAnalyticsWorkspaceArmId", + PossibleTypes = new [] { typeof(string) })] + string LogAnalyticsWorkspaceArmId { get; set; } + /// The workspace ID of the log analytics workspace to be used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The workspace ID of the log analytics workspace to be used for monitoring", + SerializedName = @"logAnalyticsWorkspaceId", + PossibleTypes = new [] { typeof(string) })] + string LogAnalyticsWorkspaceId { get; set; } + /// The shared key of the log analytics workspace that is used for monitoring + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The shared key of the log analytics workspace that is used for monitoring", + SerializedName = @"logAnalyticsWorkspaceSharedKey", + PossibleTypes = new [] { typeof(string) })] + string LogAnalyticsWorkspaceSharedKey { get; set; } + /// The name of the resource group the SAP Monitor resources get deployed into. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The name of the resource group the SAP Monitor resources get deployed into.", + SerializedName = @"managedResourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ManagedResourceGroupName { get; } + /// The subnet which the SAP monitor will be deployed in + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The subnet which the SAP monitor will be deployed in", + SerializedName = @"monitorSubnet", + PossibleTypes = new [] { typeof(string) })] + string MonitorSubnet { get; set; } + /// State of provisioning of the HanaInstance + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"State of provisioning of the HanaInstance", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; } + /// The version of the payload running in the Collector VM + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The version of the payload running in the Collector VM", + SerializedName = @"sapMonitorCollectorVersion", + PossibleTypes = new [] { typeof(string) })] + string SapMonitorCollectorVersion { get; } + + } + /// Describes the properties of a SAP monitor. + internal partial interface ISapMonitorPropertiesInternal + + { + /// The value indicating whether to send analytics to Microsoft + bool? EnableCustomerAnalytic { get; set; } + /// The ARM ID of the Log Analytics Workspace that is used for monitoring + string LogAnalyticsWorkspaceArmId { get; set; } + /// The workspace ID of the log analytics workspace to be used for monitoring + string LogAnalyticsWorkspaceId { get; set; } + /// The shared key of the log analytics workspace that is used for monitoring + string LogAnalyticsWorkspaceSharedKey { get; set; } + /// The name of the resource group the SAP Monitor resources get deployed into. + string ManagedResourceGroupName { get; set; } + /// The subnet which the SAP monitor will be deployed in + string MonitorSubnet { get; set; } + /// State of provisioning of the HanaInstance + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum? ProvisioningState { get; set; } + /// The version of the payload running in the Collector VM + string SapMonitorCollectorVersion { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.json.cs new file mode 100644 index 000000000000..679e21bf51e7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/SapMonitorProperties.json.cs @@ -0,0 +1,124 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Describes the properties of a SAP monitor. + public partial class SapMonitorProperties + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitorProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new SapMonitorProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal SapMonitorProperties(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_enableCustomerAnalytic = If( json?.PropertyT("enableCustomerAnalytics"), out var __jsonEnableCustomerAnalytics) ? (bool?)__jsonEnableCustomerAnalytics : EnableCustomerAnalytic;} + {_logAnalyticsWorkspaceArmId = If( json?.PropertyT("logAnalyticsWorkspaceArmId"), out var __jsonLogAnalyticsWorkspaceArmId) ? (string)__jsonLogAnalyticsWorkspaceArmId : (string)LogAnalyticsWorkspaceArmId;} + {_logAnalyticsWorkspaceId = If( json?.PropertyT("logAnalyticsWorkspaceId"), out var __jsonLogAnalyticsWorkspaceId) ? (string)__jsonLogAnalyticsWorkspaceId : (string)LogAnalyticsWorkspaceId;} + {_logAnalyticsWorkspaceSharedKey = If( json?.PropertyT("logAnalyticsWorkspaceSharedKey"), out var __jsonLogAnalyticsWorkspaceSharedKey) ? (string)__jsonLogAnalyticsWorkspaceSharedKey : (string)LogAnalyticsWorkspaceSharedKey;} + {_managedResourceGroupName = If( json?.PropertyT("managedResourceGroupName"), out var __jsonManagedResourceGroupName) ? (string)__jsonManagedResourceGroupName : (string)ManagedResourceGroupName;} + {_monitorSubnet = If( json?.PropertyT("monitorSubnet"), out var __jsonMonitorSubnet) ? (string)__jsonMonitorSubnet : (string)MonitorSubnet;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + {_sapMonitorCollectorVersion = If( json?.PropertyT("sapMonitorCollectorVersion"), out var __jsonSapMonitorCollectorVersion) ? (string)__jsonSapMonitorCollectorVersion : (string)SapMonitorCollectorVersion;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._enableCustomerAnalytic ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonBoolean((bool)this._enableCustomerAnalytic) : null, "enableCustomerAnalytics" ,container.Add ); + AddIf( null != (((object)this._logAnalyticsWorkspaceArmId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._logAnalyticsWorkspaceArmId.ToString()) : null, "logAnalyticsWorkspaceArmId" ,container.Add ); + AddIf( null != (((object)this._logAnalyticsWorkspaceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._logAnalyticsWorkspaceId.ToString()) : null, "logAnalyticsWorkspaceId" ,container.Add ); + AddIf( null != (((object)this._logAnalyticsWorkspaceSharedKey)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._logAnalyticsWorkspaceSharedKey.ToString()) : null, "logAnalyticsWorkspaceSharedKey" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._managedResourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._managedResourceGroupName.ToString()) : null, "managedResourceGroupName" ,container.Add ); + } + AddIf( null != (((object)this._monitorSubnet)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._monitorSubnet.ToString()) : null, "monitorSubnet" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._sapMonitorCollectorVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._sapMonitorCollectorVersion.ToString()) : null, "sapMonitorCollectorVersion" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.PowerShell.cs new file mode 100644 index 000000000000..14429e099110 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.PowerShell.cs @@ -0,0 +1,131 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Tags field of the resource. + [System.ComponentModel.TypeConverter(typeof(TagsTypeConverter))] + public partial class Tags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Tags(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.HanaOnAzure.Models.Api20200207Preview.ITags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Tags(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.HanaOnAzure.Models.Api20200207Preview.ITags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Tags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITagsInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITagsInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags1TypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Tags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITagsInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITagsInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags1TypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Tags field of the resource. + [System.ComponentModel.TypeConverter(typeof(TagsTypeConverter))] + public partial interface ITags + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.TypeConverter.cs new file mode 100644 index 000000000000..51d30793c73f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class TagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Tags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Tags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Tags.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/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.cs new file mode 100644 index 000000000000..4519d63cd978 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Tags field of the resource. + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITagsInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 _tag; + + /// Tags field of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags1()); set => this._tag = value; } + + /// Creates an new instance. + public Tags() + { + + } + } + /// Tags field of the resource. + public partial interface ITags : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// Tags field of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Tags field of the resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 Tag { get; set; } + + } + /// Tags field of the resource. + internal partial interface ITagsInternal + + { + /// Tags field of the resource. + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.json.cs new file mode 100644 index 000000000000..81384c36b8e9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Tags field of the resource. + public partial class Tags + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Tags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal Tags(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags1.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.PowerShell.cs new file mode 100644 index 000000000000..d836ea6dab32 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// Tags field of the resource. + [System.ComponentModel.TypeConverter(typeof(Tags1TypeConverter))] + public partial class Tags1 + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Tags1(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.HanaOnAzure.Models.Api20200207Preview.ITags1 DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Tags1(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.HanaOnAzure.Models.Api20200207Preview.ITags1 FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Tags1(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Tags1(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Tags field of the resource. + [System.ComponentModel.TypeConverter(typeof(Tags1TypeConverter))] + public partial interface ITags1 + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.TypeConverter.cs new file mode 100644 index 000000000000..c9bb705aa78f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class Tags1TypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Tags1.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Tags1.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Tags1.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/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.cs new file mode 100644 index 000000000000..b11e91589010 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Tags field of the resource. + public partial class Tags1 : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1Internal + { + + /// Creates an new instance. + public Tags1() + { + + } + } + /// Tags field of the resource. + public partial interface ITags1 : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + + } + /// Tags field of the resource. + internal partial interface ITags1Internal + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.dictionary.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.dictionary.cs new file mode 100644 index 000000000000..36fb7b9e99fe --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class Tags1 : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags1 source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.json.cs b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.json.cs new file mode 100644 index 000000000000..fb27c5361e86 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/Api20200207Preview/Tags1.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Tags field of the resource. + public partial class Tags1 + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new Tags1(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + /// + internal Tags1(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.PowerShell.cs b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.PowerShell.cs new file mode 100644 index 000000000000..2f80adfd9014 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.PowerShell.cs @@ -0,0 +1,152 @@ +// 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.HanaOnAzure.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(HanaOnAzureIdentityTypeConverter))] + public partial class HanaOnAzureIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HanaOnAzureIdentity(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.HanaOnAzure.Models.IHanaOnAzureIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HanaOnAzureIdentity(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.HanaOnAzure.Models.IHanaOnAzureIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HanaOnAzureIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).OperationKind = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind?) content.GetValueForProperty("OperationKind",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).OperationKind, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ProviderInstanceName = (string) content.GetValueForProperty("ProviderInstanceName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ProviderInstanceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SapMonitorName = (string) content.GetValueForProperty("SapMonitorName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SapMonitorName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Scope = (string) content.GetValueForProperty("Scope",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Scope, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).VaultName = (string) content.GetValueForProperty("VaultName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).VaultName, 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 HanaOnAzureIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).OperationKind = (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind?) content.GetValueForProperty("OperationKind",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).OperationKind, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ProviderInstanceName = (string) content.GetValueForProperty("ProviderInstanceName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ProviderInstanceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).ResourceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SapMonitorName = (string) content.GetValueForProperty("SapMonitorName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SapMonitorName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Scope = (string) content.GetValueForProperty("Scope",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).Scope, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).VaultName = (string) content.GetValueForProperty("VaultName",((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal)this).VaultName, 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.HanaOnAzure.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(HanaOnAzureIdentityTypeConverter))] + public partial interface IHanaOnAzureIdentity + + { + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.TypeConverter.cs b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.TypeConverter.cs new file mode 100644 index 000000000000..31df3979df81 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.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.HanaOnAzure.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HanaOnAzureIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity 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 HanaOnAzureIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HanaOnAzureIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HanaOnAzureIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HanaOnAzureIdentity.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/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.cs b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.cs new file mode 100644 index 000000000000..89bf2f45153d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.cs @@ -0,0 +1,216 @@ +// 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.HanaOnAzure.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class HanaOnAzureIdentity : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentityInternal + { + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _location; + + /// The location of the deleted vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind? _operationKind; + + /// Name of the operation + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind? OperationKind { get => this._operationKind; set => this._operationKind = value; } + + /// Backing field for property. + private string _providerInstanceName; + + /// Name of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ProviderInstanceName { get => this._providerInstanceName; set => this._providerInstanceName = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceName; + + /// The name of the identity resource. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string _sapMonitorName; + + /// Name of the SAP monitor resource. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string SapMonitorName { get => this._sapMonitorName; set => this._sapMonitorName = value; } + + /// Backing field for property. + private string _scope; + + /// + /// The resource provider scope of the resource. Parent resource being extended by Managed Identities. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string Scope { get => this._scope; set => this._scope = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// Name of the vault + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Origin(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.PropertyOrigin.Owned)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// Creates an new instance. + public HanaOnAzureIdentity() + { + + } + } + public partial interface IHanaOnAzureIdentity : + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IJsonSerializable + { + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The location of the deleted vault. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The location of the deleted vault.", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Name of the operation + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the operation", + SerializedName = @"operationKind", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind) })] + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind? OperationKind { get; set; } + /// Name of the provider instance. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the provider instance.", + SerializedName = @"providerInstanceName", + PossibleTypes = new [] { typeof(string) })] + string ProviderInstanceName { get; set; } + /// Name of the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroupName { get; set; } + /// The name of the identity resource. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the identity resource.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + string ResourceName { get; set; } + /// Name of the SAP monitor resource. + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + string SapMonitorName { get; set; } + /// + /// The resource provider scope of the resource. Parent resource being extended by Managed Identities. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resource provider scope of the resource. Parent resource being extended by Managed Identities.", + SerializedName = @"scope", + PossibleTypes = new [] { typeof(string) })] + string Scope { get; set; } + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + /// Name of the vault + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the vault", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + string VaultName { get; set; } + + } + internal partial interface IHanaOnAzureIdentityInternal + + { + /// Resource identity path + string Id { get; set; } + /// The location of the deleted vault. + string Location { get; set; } + /// Name of the operation + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind? OperationKind { get; set; } + /// Name of the provider instance. + string ProviderInstanceName { get; set; } + /// Name of the resource group. + string ResourceGroupName { get; set; } + /// The name of the identity resource. + string ResourceName { get; set; } + /// Name of the SAP monitor resource. + string SapMonitorName { get; set; } + /// + /// The resource provider scope of the resource. Parent resource being extended by Managed Identities. + /// + string Scope { get; set; } + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + string SubscriptionId { get; set; } + /// Name of the vault + string VaultName { get; set; } + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.json.cs b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.json.cs new file mode 100644 index 000000000000..a57f297ea1e2 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Models/HanaOnAzureIdentity.json.cs @@ -0,0 +1,123 @@ +// 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.HanaOnAzure.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + public partial class HanaOnAzureIdentity + { + + /// + /// 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.HanaOnAzure.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json ? new HanaOnAzureIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject instance to deserialize from. + internal HanaOnAzureIdentity(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_operationKind = If( json?.PropertyT("operationKind"), out var __jsonOperationKind) ? (string)__jsonOperationKind : (string)OperationKind;} + {_providerInstanceName = If( json?.PropertyT("providerInstanceName"), out var __jsonProviderInstanceName) ? (string)__jsonProviderInstanceName : (string)ProviderInstanceName;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)ResourceGroupName;} + {_resourceName = If( json?.PropertyT("resourceName"), out var __jsonResourceName) ? (string)__jsonResourceName : (string)ResourceName;} + {_sapMonitorName = If( json?.PropertyT("sapMonitorName"), out var __jsonSapMonitorName) ? (string)__jsonSapMonitorName : (string)SapMonitorName;} + {_scope = If( json?.PropertyT("scope"), out var __jsonScope) ? (string)__jsonScope : (string)Scope;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)SubscriptionId;} + {_vaultName = If( json?.PropertyT("vaultName"), out var __jsonVaultName) ? (string)__jsonVaultName : (string)VaultName;} + 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.HanaOnAzure.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != (((object)this._operationKind)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._operationKind.ToString()) : null, "operationKind" ,container.Add ); + AddIf( null != (((object)this._providerInstanceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._providerInstanceName.ToString()) : null, "providerInstanceName" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._resourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._resourceName.ToString()) : null, "resourceName" ,container.Add ); + AddIf( null != (((object)this._sapMonitorName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._sapMonitorName.ToString()) : null, "sapMonitorName" ,container.Add ); + AddIf( null != (((object)this._scope)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._scope.ToString()) : null, "scope" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._vaultName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonString(this._vaultName.ToString()) : null, "vaultName" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.Completer.cs b/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.Completer.cs new file mode 100644 index 000000000000..c776ed473943 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.Completer.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. +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for AccessPolicyUpdateKind. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKindTypeConverter))] + public partial struct AccessPolicyUpdateKind : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "add".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("add", "add", global::System.Management.Automation.CompletionResultType.ParameterValue, "add"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "replace".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("replace", "replace", global::System.Management.Automation.CompletionResultType.ParameterValue, "replace"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "remove".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("remove", "remove", global::System.Management.Automation.CompletionResultType.ParameterValue, "remove"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.TypeConverter.cs new file mode 100644 index 000000000000..d0560b5e39ce --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for AccessPolicyUpdateKind. + public partial class AccessPolicyUpdateKindTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => AccessPolicyUpdateKind.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.cs b/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.cs new file mode 100644 index 000000000000..16c66f24cad2 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/AccessPolicyUpdateKind.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + public partial struct AccessPolicyUpdateKind : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind Add = @"add"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind Remove = @"remove"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind Replace = @"replace"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Creates an instance of the + /// the value to create an instance for. + private AccessPolicyUpdateKind(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Conversion from arbitrary object to AccessPolicyUpdateKind + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new AccessPolicyUpdateKind(System.Convert.ToString(value)); + } + + /// Compares values of enum type AccessPolicyUpdateKind + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type AccessPolicyUpdateKind (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is AccessPolicyUpdateKind && Equals((AccessPolicyUpdateKind)obj); + } + + /// Returns hashCode for enum AccessPolicyUpdateKind + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Returns string representation for AccessPolicyUpdateKind + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to AccessPolicyUpdateKind + /// the value to convert to an instance of . + + public static implicit operator AccessPolicyUpdateKind(string value) + { + return new AccessPolicyUpdateKind(value); + } + + /// Implicit operator to convert AccessPolicyUpdateKind to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind e) + { + return e._value; + } + + /// Overriding != operator for enum AccessPolicyUpdateKind + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum AccessPolicyUpdateKind + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/CertificatePermissions.Completer.cs b/src/HanaOnAzure/generated/api/Support/CertificatePermissions.Completer.cs new file mode 100644 index 000000000000..bb2bde26ab05 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/CertificatePermissions.Completer.cs @@ -0,0 +1,87 @@ +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for CertificatePermissions. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissionsTypeConverter))] + public partial struct CertificatePermissions : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "get".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("get", "get", global::System.Management.Automation.CompletionResultType.ParameterValue, "get"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "list".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("list", "list", global::System.Management.Automation.CompletionResultType.ParameterValue, "list"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "delete".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("delete", "delete", global::System.Management.Automation.CompletionResultType.ParameterValue, "delete"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "create".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("create", "create", global::System.Management.Automation.CompletionResultType.ParameterValue, "create"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "import".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("import", "import", global::System.Management.Automation.CompletionResultType.ParameterValue, "import"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "update".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("update", "update", global::System.Management.Automation.CompletionResultType.ParameterValue, "update"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "managecontacts".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("managecontacts", "managecontacts", global::System.Management.Automation.CompletionResultType.ParameterValue, "managecontacts"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "getissuers".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("getissuers", "getissuers", global::System.Management.Automation.CompletionResultType.ParameterValue, "getissuers"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "listissuers".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("listissuers", "listissuers", global::System.Management.Automation.CompletionResultType.ParameterValue, "listissuers"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "setissuers".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("setissuers", "setissuers", global::System.Management.Automation.CompletionResultType.ParameterValue, "setissuers"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "deleteissuers".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("deleteissuers", "deleteissuers", global::System.Management.Automation.CompletionResultType.ParameterValue, "deleteissuers"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "manageissuers".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("manageissuers", "manageissuers", global::System.Management.Automation.CompletionResultType.ParameterValue, "manageissuers"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "recover".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("recover", "recover", global::System.Management.Automation.CompletionResultType.ParameterValue, "recover"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "purge".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("purge", "purge", global::System.Management.Automation.CompletionResultType.ParameterValue, "purge"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/CertificatePermissions.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/CertificatePermissions.TypeConverter.cs new file mode 100644 index 000000000000..aa518127b78a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/CertificatePermissions.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for CertificatePermissions. + public partial class CertificatePermissionsTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => CertificatePermissions.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/CertificatePermissions.cs b/src/HanaOnAzure/generated/api/Support/CertificatePermissions.cs new file mode 100644 index 000000000000..ce040f9dbcc9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/CertificatePermissions.cs @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// 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.HanaOnAzure.Support +{ + + public partial struct CertificatePermissions : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Create = @"create"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Delete = @"delete"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Deleteissuers = @"deleteissuers"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Get = @"get"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Getissuers = @"getissuers"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Import = @"import"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions List = @"list"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Listissuers = @"listissuers"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Managecontacts = @"managecontacts"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Manageissuers = @"manageissuers"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Purge = @"purge"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Recover = @"recover"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Setissuers = @"setissuers"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions Update = @"update"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Creates an instance of the + /// the value to create an instance for. + private CertificatePermissions(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Conversion from arbitrary object to CertificatePermissions + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new CertificatePermissions(System.Convert.ToString(value)); + } + + /// Compares values of enum type CertificatePermissions + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type CertificatePermissions (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is CertificatePermissions && Equals((CertificatePermissions)obj); + } + + /// Returns hashCode for enum CertificatePermissions + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Returns string representation for CertificatePermissions + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to CertificatePermissions + /// the value to convert to an instance of . + + public static implicit operator CertificatePermissions(string value) + { + return new CertificatePermissions(value); + } + + /// Implicit operator to convert CertificatePermissions to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions e) + { + return e._value; + } + + /// Overriding != operator for enum CertificatePermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum CertificatePermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CertificatePermissions e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/CreateMode.Completer.cs b/src/HanaOnAzure/generated/api/Support/CreateMode.Completer.cs new file mode 100644 index 000000000000..6f5c76a5cad9 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/CreateMode.Completer.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. +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for CreateMode. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateModeTypeConverter))] + public partial struct CreateMode : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "recover".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("recover", "recover", global::System.Management.Automation.CompletionResultType.ParameterValue, "recover"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "default".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("default", "default", global::System.Management.Automation.CompletionResultType.ParameterValue, "default"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/CreateMode.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/CreateMode.TypeConverter.cs new file mode 100644 index 000000000000..347fd7683a2d --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/CreateMode.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for CreateMode. + public partial class CreateModeTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => CreateMode.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/CreateMode.cs b/src/HanaOnAzure/generated/api/Support/CreateMode.cs new file mode 100644 index 000000000000..cb5a1d36b3f0 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/CreateMode.cs @@ -0,0 +1,97 @@ +// 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.HanaOnAzure.Support +{ + + public partial struct CreateMode : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode Default = @"default"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode Recover = @"recover"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to CreateMode + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new CreateMode(System.Convert.ToString(value)); + } + + /// Creates an instance of the + /// the value to create an instance for. + private CreateMode(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Compares values of enum type CreateMode + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type CreateMode (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is CreateMode && Equals((CreateMode)obj); + } + + /// Returns hashCode for enum CreateMode + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Returns string representation for CreateMode + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to CreateMode + /// the value to convert to an instance of . + + public static implicit operator CreateMode(string value) + { + return new CreateMode(value); + } + + /// Implicit operator to convert CreateMode to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode e) + { + return e._value; + } + + /// Overriding != operator for enum CreateMode + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum CreateMode + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.CreateMode e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.Completer.cs b/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.Completer.cs new file mode 100644 index 000000000000..cb4f78ee51aa --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.Completer.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// Argument completer implementation for HanaProvisioningStatesEnum. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnumTypeConverter))] + public partial struct HanaProvisioningStatesEnum : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Accepted".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Accepted", "Accepted", global::System.Management.Automation.CompletionResultType.ParameterValue, "Accepted"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Creating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Creating", "Creating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Creating"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Updating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Updating", "Updating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Updating"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Failed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Failed", "Failed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Failed"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Succeeded".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Succeeded", "Succeeded", global::System.Management.Automation.CompletionResultType.ParameterValue, "Succeeded"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Deleting".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Deleting", "Deleting", global::System.Management.Automation.CompletionResultType.ParameterValue, "Deleting"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Migrating".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Migrating", "Migrating", global::System.Management.Automation.CompletionResultType.ParameterValue, "Migrating"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.TypeConverter.cs new file mode 100644 index 000000000000..48d0563a6487 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for HanaProvisioningStatesEnum. + public partial class HanaProvisioningStatesEnumTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => HanaProvisioningStatesEnum.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.cs b/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.cs new file mode 100644 index 000000000000..6577ce8f15ec --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/HanaProvisioningStatesEnum.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. +// 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.HanaOnAzure.Support +{ + + public partial struct HanaProvisioningStatesEnum : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum Accepted = @"Accepted"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum Creating = @"Creating"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum Deleting = @"Deleting"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum Failed = @"Failed"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum Migrating = @"Migrating"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum Succeeded = @"Succeeded"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum Updating = @"Updating"; + + /// + /// the value for an instance of the Enum. + /// + private string _value { get; set; } + + /// Conversion from arbitrary object to HanaProvisioningStatesEnum + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new HanaProvisioningStatesEnum(System.Convert.ToString(value)); + } + + /// Compares values of enum type HanaProvisioningStatesEnum + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type HanaProvisioningStatesEnum (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is HanaProvisioningStatesEnum && Equals((HanaProvisioningStatesEnum)obj); + } + + /// Returns hashCode for enum HanaProvisioningStatesEnum + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private HanaProvisioningStatesEnum(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for HanaProvisioningStatesEnum + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to HanaProvisioningStatesEnum + /// the value to convert to an instance of . + + public static implicit operator HanaProvisioningStatesEnum(string value) + { + return new HanaProvisioningStatesEnum(value); + } + + /// Implicit operator to convert HanaProvisioningStatesEnum to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum e) + { + return e._value; + } + + /// Overriding != operator for enum HanaProvisioningStatesEnum + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum HanaProvisioningStatesEnum + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.HanaProvisioningStatesEnum e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/KeyPermissions.Completer.cs b/src/HanaOnAzure/generated/api/Support/KeyPermissions.Completer.cs new file mode 100644 index 000000000000..a91a3465c2d6 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/KeyPermissions.Completer.cs @@ -0,0 +1,95 @@ +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for KeyPermissions. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissionsTypeConverter))] + public partial struct KeyPermissions : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "encrypt".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("encrypt", "encrypt", global::System.Management.Automation.CompletionResultType.ParameterValue, "encrypt"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "decrypt".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("decrypt", "decrypt", global::System.Management.Automation.CompletionResultType.ParameterValue, "decrypt"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "wrapKey".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("wrapKey", "wrapKey", global::System.Management.Automation.CompletionResultType.ParameterValue, "wrapKey"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "unwrapKey".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("unwrapKey", "unwrapKey", global::System.Management.Automation.CompletionResultType.ParameterValue, "unwrapKey"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "sign".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("sign", "sign", global::System.Management.Automation.CompletionResultType.ParameterValue, "sign"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "verify".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("verify", "verify", global::System.Management.Automation.CompletionResultType.ParameterValue, "verify"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "get".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("get", "get", global::System.Management.Automation.CompletionResultType.ParameterValue, "get"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "list".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("list", "list", global::System.Management.Automation.CompletionResultType.ParameterValue, "list"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "create".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("create", "create", global::System.Management.Automation.CompletionResultType.ParameterValue, "create"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "update".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("update", "update", global::System.Management.Automation.CompletionResultType.ParameterValue, "update"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "import".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("import", "import", global::System.Management.Automation.CompletionResultType.ParameterValue, "import"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "delete".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("delete", "delete", global::System.Management.Automation.CompletionResultType.ParameterValue, "delete"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "backup".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("backup", "backup", global::System.Management.Automation.CompletionResultType.ParameterValue, "backup"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "restore".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("restore", "restore", global::System.Management.Automation.CompletionResultType.ParameterValue, "restore"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "recover".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("recover", "recover", global::System.Management.Automation.CompletionResultType.ParameterValue, "recover"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "purge".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("purge", "purge", global::System.Management.Automation.CompletionResultType.ParameterValue, "purge"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/KeyPermissions.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/KeyPermissions.TypeConverter.cs new file mode 100644 index 000000000000..615b52b362a0 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/KeyPermissions.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for KeyPermissions. + public partial class KeyPermissionsTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => KeyPermissions.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/KeyPermissions.cs b/src/HanaOnAzure/generated/api/Support/KeyPermissions.cs new file mode 100644 index 000000000000..6db499c0f61a --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/KeyPermissions.cs @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// 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.HanaOnAzure.Support +{ + + public partial struct KeyPermissions : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Backup = @"backup"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Create = @"create"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Decrypt = @"decrypt"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Delete = @"delete"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Encrypt = @"encrypt"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Get = @"get"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Import = @"import"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions List = @"list"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Purge = @"purge"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Recover = @"recover"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Restore = @"restore"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Sign = @"sign"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions UnwrapKey = @"unwrapKey"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Update = @"update"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions Verify = @"verify"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions WrapKey = @"wrapKey"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to KeyPermissions + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new KeyPermissions(System.Convert.ToString(value)); + } + + /// Compares values of enum type KeyPermissions + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type KeyPermissions (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is KeyPermissions && Equals((KeyPermissions)obj); + } + + /// Returns hashCode for enum KeyPermissions + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private KeyPermissions(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for KeyPermissions + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to KeyPermissions + /// the value to convert to an instance of . + + public static implicit operator KeyPermissions(string value) + { + return new KeyPermissions(value); + } + + /// Implicit operator to convert KeyPermissions to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions e) + { + return e._value; + } + + /// Overriding != operator for enum KeyPermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum KeyPermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.KeyPermissions e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/Reason.Completer.cs b/src/HanaOnAzure/generated/api/Support/Reason.Completer.cs new file mode 100644 index 000000000000..99c0f7e23658 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/Reason.Completer.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. +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for Reason. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.ReasonTypeConverter))] + public partial struct Reason : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "AccountNameInvalid".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("AccountNameInvalid", "AccountNameInvalid", global::System.Management.Automation.CompletionResultType.ParameterValue, "AccountNameInvalid"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "AlreadyExists".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("AlreadyExists", "AlreadyExists", global::System.Management.Automation.CompletionResultType.ParameterValue, "AlreadyExists"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/Reason.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/Reason.TypeConverter.cs new file mode 100644 index 000000000000..8a05731a539f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/Reason.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for Reason. + public partial class ReasonTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => Reason.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/Reason.cs b/src/HanaOnAzure/generated/api/Support/Reason.cs new file mode 100644 index 000000000000..e736e5260532 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/Reason.cs @@ -0,0 +1,97 @@ +// 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.HanaOnAzure.Support +{ + + public partial struct Reason : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason AccountNameInvalid = @"AccountNameInvalid"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason AlreadyExists = @"AlreadyExists"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to Reason + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new Reason(System.Convert.ToString(value)); + } + + /// Compares values of enum type Reason + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type Reason (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is Reason && Equals((Reason)obj); + } + + /// Returns hashCode for enum Reason + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private Reason(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for Reason + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to Reason + /// the value to convert to an instance of . + + public static implicit operator Reason(string value) + { + return new Reason(value); + } + + /// Implicit operator to convert Reason to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason e) + { + return e._value; + } + + /// Overriding != operator for enum Reason + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum Reason + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.Reason e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/SecretPermissions.Completer.cs b/src/HanaOnAzure/generated/api/Support/SecretPermissions.Completer.cs new file mode 100644 index 000000000000..6aeaecfa5967 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/SecretPermissions.Completer.cs @@ -0,0 +1,63 @@ +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for SecretPermissions. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissionsTypeConverter))] + public partial struct SecretPermissions : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "get".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("get", "get", global::System.Management.Automation.CompletionResultType.ParameterValue, "get"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "list".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("list", "list", global::System.Management.Automation.CompletionResultType.ParameterValue, "list"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "set".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("set", "set", global::System.Management.Automation.CompletionResultType.ParameterValue, "set"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "delete".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("delete", "delete", global::System.Management.Automation.CompletionResultType.ParameterValue, "delete"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "backup".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("backup", "backup", global::System.Management.Automation.CompletionResultType.ParameterValue, "backup"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "restore".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("restore", "restore", global::System.Management.Automation.CompletionResultType.ParameterValue, "restore"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "recover".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("recover", "recover", global::System.Management.Automation.CompletionResultType.ParameterValue, "recover"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "purge".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("purge", "purge", global::System.Management.Automation.CompletionResultType.ParameterValue, "purge"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/SecretPermissions.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/SecretPermissions.TypeConverter.cs new file mode 100644 index 000000000000..8cac212625a7 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/SecretPermissions.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for SecretPermissions. + public partial class SecretPermissionsTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => SecretPermissions.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/SecretPermissions.cs b/src/HanaOnAzure/generated/api/Support/SecretPermissions.cs new file mode 100644 index 000000000000..a423041bbdc4 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/SecretPermissions.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. +// 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.HanaOnAzure.Support +{ + + public partial struct SecretPermissions : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions Backup = @"backup"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions Delete = @"delete"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions Get = @"get"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions List = @"list"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions Purge = @"purge"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions Recover = @"recover"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions Restore = @"restore"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions Set = @"set"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to SecretPermissions + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new SecretPermissions(System.Convert.ToString(value)); + } + + /// Compares values of enum type SecretPermissions + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type SecretPermissions (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is SecretPermissions && Equals((SecretPermissions)obj); + } + + /// Returns hashCode for enum SecretPermissions + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private SecretPermissions(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for SecretPermissions + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to SecretPermissions + /// the value to convert to an instance of . + + public static implicit operator SecretPermissions(string value) + { + return new SecretPermissions(value); + } + + /// Implicit operator to convert SecretPermissions to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions e) + { + return e._value; + } + + /// Overriding != operator for enum SecretPermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum SecretPermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SecretPermissions e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/SkuName.Completer.cs b/src/HanaOnAzure/generated/api/Support/SkuName.Completer.cs new file mode 100644 index 000000000000..5413e6424e4b --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/SkuName.Completer.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. +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for SkuName. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuNameTypeConverter))] + public partial struct SkuName : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "standard".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("standard", "standard", global::System.Management.Automation.CompletionResultType.ParameterValue, "standard"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "premium".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("premium", "premium", global::System.Management.Automation.CompletionResultType.ParameterValue, "premium"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/SkuName.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/SkuName.TypeConverter.cs new file mode 100644 index 000000000000..df54ca5d9bcc --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/SkuName.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for SkuName. + public partial class SkuNameTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => SkuName.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/SkuName.cs b/src/HanaOnAzure/generated/api/Support/SkuName.cs new file mode 100644 index 000000000000..b5ab2def6bee --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/SkuName.cs @@ -0,0 +1,97 @@ +// 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.HanaOnAzure.Support +{ + + public partial struct SkuName : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName Premium = @"premium"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName Standard = @"standard"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to SkuName + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new SkuName(System.Convert.ToString(value)); + } + + /// Compares values of enum type SkuName + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type SkuName (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is SkuName && Equals((SkuName)obj); + } + + /// Returns hashCode for enum SkuName + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private SkuName(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for SkuName + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to SkuName + /// the value to convert to an instance of . + + public static implicit operator SkuName(string value) + { + return new SkuName(value); + } + + /// Implicit operator to convert SkuName to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName e) + { + return e._value; + } + + /// Overriding != operator for enum SkuName + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum SkuName + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.SkuName e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/StoragePermissions.Completer.cs b/src/HanaOnAzure/generated/api/Support/StoragePermissions.Completer.cs new file mode 100644 index 000000000000..43315982db7f --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/StoragePermissions.Completer.cs @@ -0,0 +1,87 @@ +// 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.HanaOnAzure.Support +{ + + /// Argument completer implementation for StoragePermissions. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissionsTypeConverter))] + public partial struct StoragePermissions : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "get".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("get", "get", global::System.Management.Automation.CompletionResultType.ParameterValue, "get"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "list".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("list", "list", global::System.Management.Automation.CompletionResultType.ParameterValue, "list"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "delete".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("delete", "delete", global::System.Management.Automation.CompletionResultType.ParameterValue, "delete"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "set".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("set", "set", global::System.Management.Automation.CompletionResultType.ParameterValue, "set"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "update".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("update", "update", global::System.Management.Automation.CompletionResultType.ParameterValue, "update"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "regeneratekey".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("regeneratekey", "regeneratekey", global::System.Management.Automation.CompletionResultType.ParameterValue, "regeneratekey"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "recover".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("recover", "recover", global::System.Management.Automation.CompletionResultType.ParameterValue, "recover"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "purge".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("purge", "purge", global::System.Management.Automation.CompletionResultType.ParameterValue, "purge"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "backup".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("backup", "backup", global::System.Management.Automation.CompletionResultType.ParameterValue, "backup"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "restore".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("restore", "restore", global::System.Management.Automation.CompletionResultType.ParameterValue, "restore"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "setsas".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("setsas", "setsas", global::System.Management.Automation.CompletionResultType.ParameterValue, "setsas"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "listsas".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("listsas", "listsas", global::System.Management.Automation.CompletionResultType.ParameterValue, "listsas"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "getsas".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("getsas", "getsas", global::System.Management.Automation.CompletionResultType.ParameterValue, "getsas"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "deletesas".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("deletesas", "deletesas", global::System.Management.Automation.CompletionResultType.ParameterValue, "deletesas"); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/StoragePermissions.TypeConverter.cs b/src/HanaOnAzure/generated/api/Support/StoragePermissions.TypeConverter.cs new file mode 100644 index 000000000000..fb073eb16f36 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/StoragePermissions.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support +{ + + /// TypeConverter implementation for StoragePermissions. + public partial class StoragePermissionsTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => StoragePermissions.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/api/Support/StoragePermissions.cs b/src/HanaOnAzure/generated/api/Support/StoragePermissions.cs new file mode 100644 index 000000000000..65abe1c8d731 --- /dev/null +++ b/src/HanaOnAzure/generated/api/Support/StoragePermissions.cs @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// 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.HanaOnAzure.Support +{ + + public partial struct StoragePermissions : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Backup = @"backup"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Delete = @"delete"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Deletesas = @"deletesas"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Get = @"get"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Getsas = @"getsas"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions List = @"list"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Listsas = @"listsas"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Purge = @"purge"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Recover = @"recover"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Regeneratekey = @"regeneratekey"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Restore = @"restore"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Set = @"set"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Setsas = @"setsas"; + + public static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions Update = @"update"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to StoragePermissions + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new StoragePermissions(System.Convert.ToString(value)); + } + + /// Compares values of enum type StoragePermissions + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type StoragePermissions (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is StoragePermissions && Equals((StoragePermissions)obj); + } + + /// Returns hashCode for enum StoragePermissions + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private StoragePermissions(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for StoragePermissions + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to StoragePermissions + /// the value to convert to an instance of . + + public static implicit operator StoragePermissions(string value) + { + return new StoragePermissions(value); + } + + /// Implicit operator to convert StoragePermissions to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions e) + { + return e._value; + } + + /// Overriding != operator for enum StoragePermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum StoragePermissions + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions e1, Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.StoragePermissions e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_Get.cs b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_Get.cs new file mode 100644 index 000000000000..22126c64ec3b --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_Get.cs @@ -0,0 +1,418 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// [OpenAPI] ProviderInstances_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzSapMonitorProviderInstance_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzSapMonitorProviderInstance_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the provider instance. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the provider instance.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the provider instance.", + SerializedName = @"providerInstanceName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProviderInstanceName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _sapMonitorName; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SapMonitorName { get => this._sapMonitorName; set => this._sapMonitorName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzSapMonitorProviderInstance_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.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProviderInstancesGet(SubscriptionId, ResourceGroupName, SapMonitorName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,SapMonitorName=SapMonitorName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_GetViaIdentity.cs b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_GetViaIdentity.cs new file mode 100644 index 000000000000..c604deb5b1d2 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_GetViaIdentity.cs @@ -0,0 +1,383 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// [OpenAPI] ProviderInstances_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzSapMonitorProviderInstance_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzSapMonitorProviderInstance_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzSapMonitorProviderInstance_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ProviderInstancesGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SapMonitorName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SapMonitorName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProviderInstanceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProviderInstanceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ProviderInstancesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SapMonitorName ?? null, InputObject.ProviderInstanceName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_List.cs b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_List.cs new file mode 100644 index 000000000000..abdf7f903201 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitorProviderInstance_List.cs @@ -0,0 +1,415 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Gets a list of provider instances in the specified SAP monitor. The operations returns various properties of each provider + /// instances. + /// + /// + /// [OpenAPI] ProviderInstances_List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzSapMonitorProviderInstance_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets a list of provider instances in the specified SAP monitor. The operations returns various properties of each provider instances.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzSapMonitorProviderInstance_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _sapMonitorName; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SapMonitorName { get => this._sapMonitorName; set => this._sapMonitorName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzSapMonitorProviderInstance_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.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProviderInstancesList(SubscriptionId, ResourceGroupName, SapMonitorName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,SapMonitorName=SapMonitorName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProviderInstancesList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_Get.cs b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_Get.cs new file mode 100644 index 000000000000..39e09d4f8dfb --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_Get.cs @@ -0,0 +1,404 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + /// + /// + /// [OpenAPI] SapMonitors_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzSapMonitor_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets properties of a SAP monitor for the specified subscription, resource group, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzSapMonitor_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SapMonitorName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzSapMonitor_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.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SapMonitorsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_GetViaIdentity.cs b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_GetViaIdentity.cs new file mode 100644 index 000000000000..e64cdaaac7ec --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_GetViaIdentity.cs @@ -0,0 +1,379 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + /// + /// + /// [OpenAPI] SapMonitors_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzSapMonitor_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets properties of a SAP monitor for the specified subscription, resource group, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzSapMonitor_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzSapMonitor_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SapMonitorsGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SapMonitorName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SapMonitorName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SapMonitorsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SapMonitorName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_List.cs b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_List.cs new file mode 100644 index 000000000000..d39478f502a2 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzSapMonitor_List.cs @@ -0,0 +1,386 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + /// + /// + /// [OpenAPI] SapMonitors_List=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.HanaOnAzure/sapMonitors" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzSapMonitor_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzSapMonitor_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzSapMonitor_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.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SapMonitorsList(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SapMonitorsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_Get.cs b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_Get.cs new file mode 100644 index 000000000000..188e97fba563 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_Get.cs @@ -0,0 +1,402 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Gets the identity. + /// + /// [OpenAPI] UserAssignedIdentities_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzUserAssignedIdentity_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets the identity.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzUserAssignedIdentity_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceName; + + /// The name of the identity resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the identity resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the identity resource.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzUserAssignedIdentity_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.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesGet(SubscriptionId, ResourceGroupName, ResourceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ResourceName=ResourceName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_GetViaIdentity.cs b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_GetViaIdentity.cs new file mode 100644 index 000000000000..4b1ba2833382 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_GetViaIdentity.cs @@ -0,0 +1,378 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Gets the identity. + /// + /// [OpenAPI] UserAssignedIdentities_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzUserAssignedIdentity_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Gets the identity.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzUserAssignedIdentity_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzUserAssignedIdentity_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UserAssignedIdentitiesGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UserAssignedIdentitiesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ResourceName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_List.cs b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_List.cs new file mode 100644 index 000000000000..b7b655797313 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_List.cs @@ -0,0 +1,387 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Lists all the userAssignedIdentities available under the specified subscription. + /// + /// + /// [OpenAPI] UserAssignedIdentities_ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.ManagedIdentity/userAssignedIdentities" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzUserAssignedIdentity_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Lists all the userAssignedIdentities available under the specified subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzUserAssignedIdentity_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzUserAssignedIdentity_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.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_List1.cs b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_List1.cs new file mode 100644 index 000000000000..8bd446c67db8 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/GetAzUserAssignedIdentity_List1.cs @@ -0,0 +1,401 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Lists all the userAssignedIdentities available under the specified ResourceGroup. + /// + /// + /// [OpenAPI] UserAssignedIdentities_ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzUserAssignedIdentity_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Lists all the userAssignedIdentities available under the specified ResourceGroup.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class GetAzUserAssignedIdentity_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzUserAssignedIdentity_List1() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/NewAzSapMonitorProviderInstance_CreateExpanded.cs b/src/HanaOnAzure/generated/cmdlets/NewAzSapMonitorProviderInstance_CreateExpanded.cs new file mode 100644 index 000000000000..295da6aaa618 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/NewAzSapMonitorProviderInstance_CreateExpanded.cs @@ -0,0 +1,526 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// [OpenAPI] ProviderInstances_Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzSapMonitorProviderInstance_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class NewAzSapMonitorProviderInstance_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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; } } + + /// A JSON string containing metadata of the provider instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A JSON string containing metadata of the provider instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A JSON string containing metadata of the provider instance.", + SerializedName = @"metadata", + PossibleTypes = new [] { typeof(string) })] + public string Metadata { get => ProviderInstanceParameterBody.Metadata ?? null; set => ProviderInstanceParameterBody.Metadata = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the provider instance. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the provider instance.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the provider instance.", + SerializedName = @"providerInstanceName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProviderInstanceName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance _providerInstanceParameterBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ProviderInstance(); + + /// A provider instance associated with a SAP monitor. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance ProviderInstanceParameterBody { get => this._providerInstanceParameterBody; set => this._providerInstanceParameterBody = value; } + + /// A JSON string containing the properties of the provider instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "A JSON string containing the properties of the provider instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"A JSON string containing the properties of the provider instance.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(string) })] + public string ProviderInstanceProperty { get => ProviderInstanceParameterBody.ProviderInstanceProperty ?? null; set => ProviderInstanceParameterBody.ProviderInstanceProperty = value; } + + /// The type of provider instance. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The type of provider instance.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The type of provider instance.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + public string ProviderType { get => ProviderInstanceParameterBody.PropertiesType ?? null; set => ProviderInstanceParameterBody.PropertiesType = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _sapMonitorName; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SapMonitorName { get => this._sapMonitorName; set => this._sapMonitorName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzSapMonitorProviderInstance_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets.NewAzSapMonitorProviderInstance_CreateExpanded Clone() + { + var clone = new NewAzSapMonitorProviderInstance_CreateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.ProviderInstanceParameterBody = this.ProviderInstanceParameterBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.SapMonitorName = this.SapMonitorName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzSapMonitorProviderInstance_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProviderInstancesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProviderInstancesCreate(SubscriptionId, ResourceGroupName, SapMonitorName, Name, ProviderInstanceParameterBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,SapMonitorName=SapMonitorName,Name=Name,body=ProviderInstanceParameterBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName, Name=Name, body=ProviderInstanceParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName, Name=Name, body=ProviderInstanceParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/NewAzSapMonitor_CreateExpanded.cs b/src/HanaOnAzure/generated/cmdlets/NewAzSapMonitor_CreateExpanded.cs new file mode 100644 index 000000000000..0067f5cb0352 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/NewAzSapMonitor_CreateExpanded.cs @@ -0,0 +1,557 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Creates a SAP monitor for the specified subscription, resource group, and resource name. + /// + /// + /// [OpenAPI] SapMonitors_Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzSapMonitor_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Creates a SAP monitor for the specified subscription, resource group, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class NewAzSapMonitor_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// The value indicating whether to send analytics to Microsoft + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The value indicating whether to send analytics to Microsoft")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The value indicating whether to send analytics to Microsoft", + SerializedName = @"enableCustomerAnalytics", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter EnableCustomerAnalytic { get => SapMonitorParameterBody.EnableCustomerAnalytic ?? default(global::System.Management.Automation.SwitchParameter); set => SapMonitorParameterBody.EnableCustomerAnalytic = value; } + + /// 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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The geo-location where the resource lives + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => SapMonitorParameterBody.Location ?? null; set => SapMonitorParameterBody.Location = value; } + + /// The workspace ID of the log analytics workspace to be used for monitoring + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The workspace ID of the log analytics workspace to be used for monitoring")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The workspace ID of the log analytics workspace to be used for monitoring", + SerializedName = @"logAnalyticsWorkspaceId", + PossibleTypes = new [] { typeof(string) })] + public string LogAnalyticsWorkspaceId { get => SapMonitorParameterBody.LogAnalyticsWorkspaceId ?? null; set => SapMonitorParameterBody.LogAnalyticsWorkspaceId = value; } + + /// The ARM ID of the Log Analytics Workspace that is used for monitoring + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The ARM ID of the Log Analytics Workspace that is used for monitoring")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The ARM ID of the Log Analytics Workspace that is used for monitoring", + SerializedName = @"logAnalyticsWorkspaceArmId", + PossibleTypes = new [] { typeof(string) })] + public string LogAnalyticsWorkspaceResourceId { get => SapMonitorParameterBody.LogAnalyticsWorkspaceArmId ?? null; set => SapMonitorParameterBody.LogAnalyticsWorkspaceArmId = value; } + + /// The shared key of the log analytics workspace that is used for monitoring + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The shared key of the log analytics workspace that is used for monitoring")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The shared key of the log analytics workspace that is used for monitoring", + SerializedName = @"logAnalyticsWorkspaceSharedKey", + PossibleTypes = new [] { typeof(string) })] + public string LogAnalyticsWorkspaceSharedKey { get => SapMonitorParameterBody.LogAnalyticsWorkspaceSharedKey ?? null; set => SapMonitorParameterBody.LogAnalyticsWorkspaceSharedKey = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The subnet which the SAP monitor will be deployed in. It should be the same subnet of HANA database. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The subnet which the SAP monitor will be deployed in. It should be the same subnet of HANA database.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The subnet which the SAP monitor will be deployed in. It should be the same subnet of HANA database.", + SerializedName = @"monitorSubnet", + PossibleTypes = new [] { typeof(string) })] + public string MonitorSubnetResourceId { get => SapMonitorParameterBody.MonitorSubnet ?? null; set => SapMonitorParameterBody.MonitorSubnet = value; } + + /// Backing field for property. + private string _name; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SapMonitorName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor _sapMonitorParameterBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.SapMonitor(); + + /// SAP monitor info on Azure (ARM properties and SAP monitor properties) + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor SapMonitorParameterBody { get => this._sapMonitorParameterBody; set => this._sapMonitorParameterBody = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get => SapMonitorParameterBody.Tag ?? null /* object */; set => SapMonitorParameterBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzSapMonitor_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets.NewAzSapMonitor_CreateExpanded Clone() + { + var clone = new NewAzSapMonitor_CreateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SapMonitorParameterBody = this.SapMonitorParameterBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzSapMonitor_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SapMonitorsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SapMonitorsCreate(SubscriptionId, ResourceGroupName, Name, SapMonitorParameterBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=SapMonitorParameterBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=SapMonitorParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=SapMonitorParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/NewAzUserAssignedIdentity_CreateExpanded.cs b/src/HanaOnAzure/generated/cmdlets/NewAzUserAssignedIdentity_CreateExpanded.cs new file mode 100644 index 000000000000..894800797a20 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/NewAzUserAssignedIdentity_CreateExpanded.cs @@ -0,0 +1,467 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Create or update an identity in the specified subscription and resource group. + /// + /// [OpenAPI] UserAssignedIdentities_CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzUserAssignedIdentity_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Create or update an identity in the specified subscription and resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class NewAzUserAssignedIdentity_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The geo-location where the resource lives + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ParametersBody.Location ?? null; set => ParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity(); + + /// Describes an identity resource. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceName; + + /// The name of the identity resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the identity resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the identity resource.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } + + /// + /// 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 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 from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzUserAssignedIdentity_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UserAssignedIdentitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesCreateOrUpdate(SubscriptionId, ResourceGroupName, ResourceName, ParametersBody, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ResourceName=ResourceName,body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// 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 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.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitorProviderInstance_Delete.cs b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitorProviderInstance_Delete.cs new file mode 100644 index 000000000000..89063ac7b9df --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitorProviderInstance_Delete.cs @@ -0,0 +1,524 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// [OpenAPI] ProviderInstances_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzSapMonitorProviderInstance_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class RemoveAzSapMonitorProviderInstance_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the provider instance. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the provider instance.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the provider instance.", + SerializedName = @"providerInstanceName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("ProviderInstanceName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _sapMonitorName; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SapMonitorName { get => this._sapMonitorName; set => this._sapMonitorName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzSapMonitorProviderInstance_Delete + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets.RemoveAzSapMonitorProviderInstance_Delete Clone() + { + var clone = new RemoveAzSapMonitorProviderInstance_Delete(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.SapMonitorName = this.SapMonitorName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProviderInstancesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.ProviderInstancesDelete(SubscriptionId, ResourceGroupName, SapMonitorName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,SapMonitorName=SapMonitorName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzSapMonitorProviderInstance_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, SapMonitorName=SapMonitorName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitorProviderInstance_DeleteViaIdentity.cs b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitorProviderInstance_DeleteViaIdentity.cs new file mode 100644 index 000000000000..d84761fbddd5 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitorProviderInstance_DeleteViaIdentity.cs @@ -0,0 +1,488 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + /// + /// + /// [OpenAPI] ProviderInstances_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}/providerInstances/{providerInstanceName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzSapMonitorProviderInstance_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class RemoveAzSapMonitorProviderInstance_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzSapMonitorProviderInstance_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets.RemoveAzSapMonitorProviderInstance_DeleteViaIdentity Clone() + { + var clone = new RemoveAzSapMonitorProviderInstance_DeleteViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'ProviderInstancesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.ProviderInstancesDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SapMonitorName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SapMonitorName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProviderInstanceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProviderInstanceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.ProviderInstancesDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SapMonitorName ?? null, InputObject.ProviderInstanceName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzSapMonitorProviderInstance_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitor_Delete.cs b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitor_Delete.cs new file mode 100644 index 000000000000..b3e90e3b76fa --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitor_Delete.cs @@ -0,0 +1,509 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + /// + /// + /// [OpenAPI] SapMonitors_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzSapMonitor_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Deletes a SAP monitor with the specified subscription, resource group, and monitor name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class RemoveAzSapMonitor_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SapMonitorName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzSapMonitor_Delete + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets.RemoveAzSapMonitor_Delete Clone() + { + var clone = new RemoveAzSapMonitor_Delete(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SapMonitorsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SapMonitorsDelete(SubscriptionId, ResourceGroupName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzSapMonitor_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitor_DeleteViaIdentity.cs b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitor_DeleteViaIdentity.cs new file mode 100644 index 000000000000..5dfec7476e57 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/RemoveAzSapMonitor_DeleteViaIdentity.cs @@ -0,0 +1,484 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + /// + /// + /// [OpenAPI] SapMonitors_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzSapMonitor_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Deletes a SAP monitor with the specified subscription, resource group, and monitor name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class RemoveAzSapMonitor_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzSapMonitor_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Cmdlets.RemoveAzSapMonitor_DeleteViaIdentity Clone() + { + var clone = new RemoveAzSapMonitor_DeleteViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SapMonitorsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SapMonitorsDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SapMonitorName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SapMonitorName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SapMonitorsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SapMonitorName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzSapMonitor_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/RemoveAzUserAssignedIdentity_Delete.cs b/src/HanaOnAzure/generated/cmdlets/RemoveAzUserAssignedIdentity_Delete.cs new file mode 100644 index 000000000000..9526d81a6b08 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/RemoveAzUserAssignedIdentity_Delete.cs @@ -0,0 +1,441 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Deletes the identity. + /// + /// [OpenAPI] UserAssignedIdentities_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzUserAssignedIdentity_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Deletes the identity.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class RemoveAzUserAssignedIdentity_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceName; + + /// The name of the identity resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the identity resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the identity resource.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UserAssignedIdentitiesDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesDelete(SubscriptionId, ResourceGroupName, ResourceName, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ResourceName=ResourceName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzUserAssignedIdentity_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/RemoveAzUserAssignedIdentity_DeleteViaIdentity.cs b/src/HanaOnAzure/generated/cmdlets/RemoveAzUserAssignedIdentity_DeleteViaIdentity.cs new file mode 100644 index 000000000000..d02ac19f1ce0 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/RemoveAzUserAssignedIdentity_DeleteViaIdentity.cs @@ -0,0 +1,420 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Deletes the identity. + /// + /// [OpenAPI] UserAssignedIdentities_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzUserAssignedIdentity_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Deletes the identity.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class RemoveAzUserAssignedIdentity_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UserAssignedIdentitiesDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UserAssignedIdentitiesDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UserAssignedIdentitiesDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ResourceName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzUserAssignedIdentity_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/SetAzUserAssignedIdentity_UpdateExpanded.cs b/src/HanaOnAzure/generated/cmdlets/SetAzUserAssignedIdentity_UpdateExpanded.cs new file mode 100644 index 000000000000..fa66bb2e3f18 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/SetAzUserAssignedIdentity_UpdateExpanded.cs @@ -0,0 +1,467 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Create or update an identity in the specified subscription and resource group. + /// + /// [OpenAPI] UserAssignedIdentities_CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzUserAssignedIdentity_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Create or update an identity in the specified subscription and resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class SetAzUserAssignedIdentity_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The geo-location where the resource lives + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ParametersBody.Location ?? null; set => ParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.Identity(); + + /// Describes an identity resource. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceName; + + /// The name of the identity resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the identity resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the identity resource.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } + + /// + /// 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 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 from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UserAssignedIdentitiesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesCreateOrUpdate(SubscriptionId, ResourceGroupName, ResourceName, ParametersBody, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ResourceName=ResourceName,body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public SetAzUserAssignedIdentity_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// 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 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.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/SetAzVaultAccessPolicy_UpdateExpanded.cs b/src/HanaOnAzure/generated/cmdlets/SetAzVaultAccessPolicy_UpdateExpanded.cs new file mode 100644 index 000000000000..bc770603a49e --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/SetAzVaultAccessPolicy_UpdateExpanded.cs @@ -0,0 +1,420 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Update access policies in a key vault in the specified subscription. + /// + /// [OpenAPI] Vaults_UpdateAccessPolicy=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/accessPolicies/{operationKind}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzVaultAccessPolicy_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Update access policies in a key vault in the specified subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class SetAzVaultAccessPolicy_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// + /// An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant + /// ID as the key vault's tenant ID. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.", + SerializedName = @"accessPolicies", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[] AccessPolicy { get => ParametersBody.AccessPolicy ?? null /* arrayOf */; set => ParametersBody.AccessPolicy = value; } + + /// 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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind _operationKind; + + /// Name of the operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the operation")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the operation", + SerializedName = @"operationKind", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind))] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind OperationKind { get => this._operationKind; set => this._operationKind = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.VaultAccessPolicyParameters(); + + /// Parameters for updating the access policy in a vault + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the Resource Group to which the vault belongs. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the Resource Group to which the vault belongs.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group to which the vault belongs.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _vaultName; + + /// Name of the vault + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the vault")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the vault", + SerializedName = @"vaultName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string VaultName { get => this._vaultName; set => this._vaultName = value; } + + /// + /// 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 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); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'VaultsUpdateAccessPolicy' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.VaultsUpdateAccessPolicy(ResourceGroupName, VaultName, OperationKind, SubscriptionId, ParametersBody, onOk, onCreated, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,VaultName=VaultName,OperationKind=OperationKind,SubscriptionId=SubscriptionId,body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public SetAzVaultAccessPolicy_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// 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 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.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters + WriteObject((await response)); + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/UpdateAzSapMonitor_UpdateExpanded.cs b/src/HanaOnAzure/generated/cmdlets/UpdateAzSapMonitor_UpdateExpanded.cs new file mode 100644 index 000000000000..2a57b6c4df61 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/UpdateAzSapMonitor_UpdateExpanded.cs @@ -0,0 +1,422 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + /// + /// + /// [OpenAPI] SapMonitors_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzSapMonitor_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class UpdateAzSapMonitor_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the SAP monitor resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the SAP monitor resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the SAP monitor resource.", + SerializedName = @"sapMonitorName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SapMonitorName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Tags field of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Tags field of the resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Tags field of the resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 Tag { get => TagsParameterBody.Tag ?? null /* object */; set => TagsParameterBody.Tag = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags _tagsParameterBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags(); + + /// Tags field of the resource. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags TagsParameterBody { get => this._tagsParameterBody; set => this._tagsParameterBody = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SapMonitorsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SapMonitorsUpdate(SubscriptionId, ResourceGroupName, Name, TagsParameterBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=TagsParameterBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzSapMonitor_UpdateExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=TagsParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=TagsParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/UpdateAzSapMonitor_UpdateViaIdentityExpanded.cs b/src/HanaOnAzure/generated/cmdlets/UpdateAzSapMonitor_UpdateViaIdentityExpanded.cs new file mode 100644 index 000000000000..dcff032f2a2b --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/UpdateAzSapMonitor_UpdateViaIdentityExpanded.cs @@ -0,0 +1,400 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// + /// Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + /// + /// + /// [OpenAPI] SapMonitors_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzSapMonitor_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class UpdateAzSapMonitor_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Tags field of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Tags field of the resource.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Tags field of the resource.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags1 Tag { get => TagsParameterBody.Tag ?? null /* object */; set => TagsParameterBody.Tag = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags _tagsParameterBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.Tags(); + + /// Tags field of the resource. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ITags TagsParameterBody { get => this._tagsParameterBody; set => this._tagsParameterBody = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SapMonitorsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SapMonitorsUpdateViaIdentity(InputObject.Id, TagsParameterBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SapMonitorName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SapMonitorName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SapMonitorsUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SapMonitorName ?? null, TagsParameterBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=TagsParameterBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzSapMonitor_UpdateViaIdentityExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=TagsParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=TagsParameterBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/UpdateAzUserAssignedIdentity_UpdateExpanded.cs b/src/HanaOnAzure/generated/cmdlets/UpdateAzUserAssignedIdentity_UpdateExpanded.cs new file mode 100644 index 000000000000..8306f15fc5da --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/UpdateAzUserAssignedIdentity_UpdateExpanded.cs @@ -0,0 +1,431 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Update an identity in the specified subscription and resource group. + /// + /// [OpenAPI] UserAssignedIdentities_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzUserAssignedIdentity_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Update an identity in the specified subscription and resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class UpdateAzUserAssignedIdentity_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The geo-location where the resource lives + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ParametersBody.Location ?? null; set => ParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdate(); + + /// Describes an identity resource. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// Name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceName; + + /// The name of the identity resource. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the identity resource.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the identity resource.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every + /// service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UserAssignedIdentitiesUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.UserAssignedIdentitiesUpdate(SubscriptionId, ResourceGroupName, ResourceName, ParametersBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ResourceName=ResourceName,body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzUserAssignedIdentity_UpdateExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ResourceName=ResourceName, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/cmdlets/UpdateAzUserAssignedIdentity_UpdateViaIdentityExpanded.cs b/src/HanaOnAzure/generated/cmdlets/UpdateAzUserAssignedIdentity_UpdateViaIdentityExpanded.cs new file mode 100644 index 000000000000..8028fd4f9331 --- /dev/null +++ b/src/HanaOnAzure/generated/cmdlets/UpdateAzUserAssignedIdentity_UpdateViaIdentityExpanded.cs @@ -0,0 +1,410 @@ +// 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.HanaOnAzure.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Extensions; + + /// Update an identity in the specified subscription and resource group. + /// + /// [OpenAPI] UserAssignedIdentities_Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{resourceName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzUserAssignedIdentity_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity))] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Description(@"Update an identity in the specified subscription and resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Generated] + public partial class UpdateAzUserAssignedIdentity_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.HanaOnAzure Client => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// The geo-location where the resource lives + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ParametersBody.Location ?? null; set => ParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IdentityUpdate(); + + /// Describes an identity resource. + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdate ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category(global::Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'UserAssignedIdentitiesUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.UserAssignedIdentitiesUpdateViaIdentity(InputObject.Id, ParametersBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.UserAssignedIdentitiesUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ResourceName ?? null, ParametersBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzUserAssignedIdentity_UpdateViaIdentityExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/AsyncCommandRuntime.cs b/src/HanaOnAzure/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 000000000000..6c912448a57e --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,828 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/runtime/AsyncJob.cs b/src/HanaOnAzure/generated/runtime/AsyncJob.cs new file mode 100644 index 000000000000..2dba3206c42b --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/AsyncOperationResponse.cs b/src/HanaOnAzure/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 000000000000..c6657c5e058f --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 000000000000..1f55e338bb7f --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 000000000000..d538f875410b --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 000000000000..df7c6f665a28 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,99 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support"; + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!IsAzure || pf.Property.Name != "Id") + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = viewParameters.Type.FullName + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 000000000000..da73410aa2a8 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 000000000000..309a1c0fac9c --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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.HanaOnAzure.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 000000000000..5fbe4d0c00bd --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + protected override void ProcessRecord() + { + try { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append(@" +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +"); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder); + } + } + } catch (Exception ee) { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 000000000000..78f24fde55e0 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.0"); + // 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.HanaOnAzure.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: HanaOn cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.HanaOnAzure.private.dll"}'"); + + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.HanaOnAzure.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = {previewVersion}"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule HanaOn".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/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 000000000000..0569c9a5e785 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine(@"$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath)" +); + sb.AppendLine($@"$TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@"$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName +"); + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 000000000000..ab3ad54ef150 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 000000000000..047fc00cf4c5 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 000000000000..e915bd25f4cc --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/CollectionExtensions.cs b/src/HanaOnAzure/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 000000000000..50ace417339d --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/BuildTime/MarkdownRenderer.cs b/src/HanaOnAzure/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 000000000000..fbc228916a6b --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + if (markdownInfo.SupportsPaging) + { + foreach (var parameter in SupportsPagingParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"### {alias}{Environment.NewLine}{Environment.NewLine}"); + } + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"{relatedLink}{Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 000000000000..50885470e1aa --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 000000000000..a6e2467516e9 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() => $@"{ExampleNameHeader}{ExampleInfo.Name} +{ExampleCodeHeader} +{ExampleInfo.Code} +{ExampleCodeFooter} + +{ExampleInfo.Description.ToDescriptionFormat()} + +"; + } + + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Description.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 000000000000..694680f409de --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 000000000000..7a73b8c9050f --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,291 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public string[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + RelatedLinks = commentInfo.RelatedLinks; + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (codeEndIndex ?? 0) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + if (Variant.SupportsPaging) + { + parameterStrings = parameterStrings.Append(" [-First ]").Append(" [-IncludeTotalCount]").Append(" [-Skip ]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string description) + { + Name = name; + Code = code; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}") + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 000000000000..68d7325a6218 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,513 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BeginOutput + { + public VariantGroup VariantGroup { get; } + + public BeginOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}')) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + return sb.ToString(); + } + } + + internal class ProcessOutput + { + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + } + + internal class EndOutput + { + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new [] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new []{"
", "\r\n", "\n"}); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => new ArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, !isFirst && includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 000000000000..4c60e9c80a70 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,499 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}To construct, see NOTES section for {complexParameterName} properties and create a hash table."; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines().Replace(complexMessage, String.Empty).Replace(complexMessage.ToPsSingleLine(), String.Empty); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[]{} : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + + private const string HelpLinkPrefix = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{variantGroup.ModuleName.ToLowerInvariant()}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => !ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)); + } + return parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))).ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/PsAttributes.cs b/src/HanaOnAzure/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 000000000000..87a58e313e9d --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/PsExtensions.cs b/src/HanaOnAzure/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 000000000000..5fd868d26a26 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal static class PsExtensions + { + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/PsHelpers.cs b/src/HanaOnAzure/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 000000000000..cd58a2f1085b --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path '{scriptFolder}' -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.StartsWith(GuidStart))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/src/HanaOnAzure/generated/runtime/BuildTime/StringExtensions.cs b/src/HanaOnAzure/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 000000000000..168cf9c49a40 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/BuildTime/XmlExtensions.cs b/src/HanaOnAzure/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 000000000000..e89e3bc53bb5 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/CmdInfoHandler.cs b/src/HanaOnAzure/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 000000000000..fac27b4d8f9d --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/ConversionException.cs b/src/HanaOnAzure/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 000000000000..367a217d219d --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/IJsonConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 000000000000..f33ab91c935a --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Conversions/Instances/BinaryConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 000000000000..5f482d7c912b --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/BooleanConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 000000000000..88f12d45c8fc --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 000000000000..928df40148e1 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 000000000000..27bbf0332710 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/DecimalConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 000000000000..5a370a56e85a --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/DoubleConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 000000000000..a100f86742c1 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/EnumConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 000000000000..1d86e5ca2400 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/GuidConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 000000000000..c2fea24e2013 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 000000000000..3e893006f513 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/Int16Converter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 000000000000..59b59174ee53 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/Int32Converter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 000000000000..2322a8490b38 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/Int64Converter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 000000000000..7e81b0f800c0 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 000000000000..c04c2100da00 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 000000000000..2ac215482258 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/SingleConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 000000000000..e579ef32b174 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/StringConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 000000000000..e7d553fa6a03 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 000000000000..3c09ee1f1994 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/UInt16Converter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 000000000000..9550a5232642 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/UInt32Converter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 000000000000..1665bc9a4589 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/UInt64Converter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 000000000000..56a29373eef9 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/Instances/UriConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 000000000000..c46af71009fe --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/JsonConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 000000000000..be882c8cfab4 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/JsonConverterAttribute.cs b/src/HanaOnAzure/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 000000000000..45748da27ad2 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/JsonConverterFactory.cs b/src/HanaOnAzure/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 000000000000..beec6a87af26 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Conversions/StringLikeConverter.cs b/src/HanaOnAzure/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 000000000000..96d5d5fe9606 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Customizations/IJsonSerializable.cs b/src/HanaOnAzure/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 000000000000..7527d0603f6c --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Customizations/JsonArray.cs b/src/HanaOnAzure/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 000000000000..89b6da38c494 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Customizations/JsonBoolean.cs b/src/HanaOnAzure/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 000000000000..b7ee74f51fcf --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Customizations/JsonNode.cs b/src/HanaOnAzure/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 000000000000..a794fde96636 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Customizations/JsonNumber.cs b/src/HanaOnAzure/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 000000000000..dfc97bd51329 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Customizations/JsonObject.cs b/src/HanaOnAzure/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 000000000000..39ca3a2b07a1 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/runtime/Customizations/JsonString.cs b/src/HanaOnAzure/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 000000000000..523e84f71c64 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Customizations/XNodeArray.cs b/src/HanaOnAzure/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 000000000000..397210a38288 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Debugging.cs b/src/HanaOnAzure/generated/runtime/Debugging.cs new file mode 100644 index 000000000000..536bbce68815 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/DictionaryExtensions.cs b/src/HanaOnAzure/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 000000000000..b19e5b5cecc7 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + if (value is System.Collections.Hashtable nested) + { + HashTableToDictionary(nested, new System.Collections.Generic.Dictionary()); + } + else + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/EventData.cs b/src/HanaOnAzure/generated/runtime/EventData.cs new file mode 100644 index 000000000000..0bbd1859399d --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/EventDataExtensions.cs b/src/HanaOnAzure/generated/runtime/EventDataExtensions.cs new file mode 100644 index 000000000000..80ed7da72a18 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime +{ + using System; + + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/EventListener.cs b/src/HanaOnAzure/generated/runtime/EventListener.cs new file mode 100644 index 000000000000..67251a7aa7f6 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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.HanaOnAzure.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/generated/runtime/Events.cs b/src/HanaOnAzure/generated/runtime/Events.cs new file mode 100644 index 000000000000..96089da4bc33 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/EventsExtensions.cs b/src/HanaOnAzure/generated/runtime/EventsExtensions.cs new file mode 100644 index 000000000000..ed89239d3cac --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Extensions.cs b/src/HanaOnAzure/generated/runtime/Extensions.cs new file mode 100644 index 000000000000..13d5f276eb4d --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/Extensions.cs @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + using System.Linq; + + internal static partial class Extensions + { + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => headerName == each.Key).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/src/HanaOnAzure/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 000000000000..ce0812ab8309 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/src/HanaOnAzure/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 000000000000..63463d899b4b --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Helpers/Seperator.cs b/src/HanaOnAzure/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 000000000000..c669e064c44c --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Helpers/TypeDetails.cs b/src/HanaOnAzure/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 000000000000..d03afc3b7ff7 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Helpers/XHelper.cs b/src/HanaOnAzure/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 000000000000..7f86a543e161 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/HttpPipeline.cs b/src/HanaOnAzure/generated/runtime/HttpPipeline.cs new file mode 100644 index 000000000000..edd549c7e033 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/HttpPipelineMocking.ps1 b/src/HanaOnAzure/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 000000000000..5f956e39aeb3 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/IAssociativeArray.cs b/src/HanaOnAzure/generated/runtime/IAssociativeArray.cs new file mode 100644 index 000000000000..d3db50d55bfd --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + int Count { get; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/IHeaderSerializable.cs b/src/HanaOnAzure/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 000000000000..c92826f318b4 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/ISendAsync.cs b/src/HanaOnAzure/generated/runtime/ISendAsync.cs new file mode 100644 index 000000000000..058cb7a79245 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/ISendAsync.cs @@ -0,0 +1,289 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/InfoAttribute.cs b/src/HanaOnAzure/generated/runtime/InfoAttribute.cs new file mode 100644 index 000000000000..258693745843 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/InfoAttribute.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Iso/IsoDate.cs b/src/HanaOnAzure/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 000000000000..3b02cd09abc1 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/JsonType.cs b/src/HanaOnAzure/generated/runtime/JsonType.cs new file mode 100644 index 000000000000..394a82ae8f71 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Method.cs b/src/HanaOnAzure/generated/runtime/Method.cs new file mode 100644 index 000000000000..62cce2f0aed5 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Models/JsonMember.cs b/src/HanaOnAzure/generated/runtime/Models/JsonMember.cs new file mode 100644 index 000000000000..ba2af735b881 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Models/JsonModel.cs b/src/HanaOnAzure/generated/runtime/Models/JsonModel.cs new file mode 100644 index 000000000000..7b541ff78ca3 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Models/JsonModelCache.cs b/src/HanaOnAzure/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 000000000000..48ddc721efd7 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/Collections/JsonArray.cs b/src/HanaOnAzure/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 000000000000..fde2bac668e8 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/Collections/XImmutableArray.cs b/src/HanaOnAzure/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 000000000000..90b8ca1b17d4 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/Collections/XList.cs b/src/HanaOnAzure/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 000000000000..20d916d717e8 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/Collections/XNodeArray.cs b/src/HanaOnAzure/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 000000000000..db2df248ad9d --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Nodes/Collections/XSet.cs b/src/HanaOnAzure/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 000000000000..bbb2e91b0a72 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/JsonBoolean.cs b/src/HanaOnAzure/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 000000000000..a4f0accc452b --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/JsonDate.cs b/src/HanaOnAzure/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 000000000000..5c2ba5ba59e5 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/JsonNode.cs b/src/HanaOnAzure/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 000000000000..ca9d97fb85b6 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/JsonNumber.cs b/src/HanaOnAzure/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 000000000000..917d774f6c5b --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Nodes/JsonObject.cs b/src/HanaOnAzure/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 000000000000..7266247206ea --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/JsonString.cs b/src/HanaOnAzure/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 000000000000..c6323602e038 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/XBinary.cs b/src/HanaOnAzure/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 000000000000..be98d5f20c1f --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Nodes/XNull.cs b/src/HanaOnAzure/generated/runtime/Nodes/XNull.cs new file mode 100644 index 000000000000..3e1ade56085c --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Parser/Exceptions/ParseException.cs b/src/HanaOnAzure/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 000000000000..0950a03963fe --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Parser/JsonParser.cs b/src/HanaOnAzure/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 000000000000..28ca2704157a --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Parser/JsonToken.cs b/src/HanaOnAzure/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 000000000000..d97a414af448 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Parser/JsonTokenizer.cs b/src/HanaOnAzure/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 000000000000..dc7fcc25cfa8 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Parser/Location.cs b/src/HanaOnAzure/generated/runtime/Parser/Location.cs new file mode 100644 index 000000000000..c9ff8b6a77bb --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Parser/Readers/SourceReader.cs b/src/HanaOnAzure/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 000000000000..ae434415dab0 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Parser/TokenReader.cs b/src/HanaOnAzure/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 000000000000..9d5ac2254549 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/PipelineMocking.cs b/src/HanaOnAzure/generated/runtime/PipelineMocking.cs new file mode 100644 index 000000000000..cfe99c41de0b --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/PipelineMocking.cs @@ -0,0 +1,254 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result); + + internal static JsonNode SerializeContent(byte[] content) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (content.EndsWith("==")) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content) }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content) }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"))) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"))) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Response.cs b/src/HanaOnAzure/generated/runtime/Response.cs new file mode 100644 index 000000000000..a64d99daba01 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Serialization/JsonSerializer.cs b/src/HanaOnAzure/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 000000000000..75496757fae6 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Serialization/PropertyTransformation.cs b/src/HanaOnAzure/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 000000000000..04a916075dae --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/Serialization/SerializationOptions.cs b/src/HanaOnAzure/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 000000000000..9736d6ed28fa --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/SerializationMode.cs b/src/HanaOnAzure/generated/runtime/SerializationMode.cs new file mode 100644 index 000000000000..c8425a711188 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/SerializationMode.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeReadOnly = 1 << 1, + + IncludeAll = IncludeHeaders | IncludeReadOnly + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/TypeConverterExtensions.cs b/src/HanaOnAzure/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 000000000000..8f4d45db182a --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + } +} diff --git a/src/HanaOnAzure/generated/runtime/UndeclaredResponseException.cs b/src/HanaOnAzure/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 000000000000..3b1e021a6d71 --- /dev/null +++ b/src/HanaOnAzure/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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.HanaOnAzure.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Json.JsonObject; + + // see if there is an error block in the body + json = json.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // we'll create one below. + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/generated/runtime/Writers/JsonWriter.cs b/src/HanaOnAzure/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 000000000000..09542f6e6a97 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/generated/runtime/delegates.cs b/src/HanaOnAzure/generated/runtime/delegates.cs new file mode 100644 index 000000000000..b3915480c9e3 --- /dev/null +++ b/src/HanaOnAzure/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.HanaOnAzure.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/HanaOnAzure/help/Az.HanaOnAzure.md b/src/HanaOnAzure/help/Az.HanaOnAzure.md new file mode 100644 index 000000000000..58b8bc2c8052 --- /dev/null +++ b/src/HanaOnAzure/help/Az.HanaOnAzure.md @@ -0,0 +1,34 @@ +--- +Module Name: Az.HanaOnAzure +Module Guid: 79ad50da-e6b5-4703-885a-d36974a4d9b9 +Download Help Link: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure +Help Version: 1.0.0.0 +Locale: en-US +--- + +# Az.HanaOnAzure Module +## Description +Microsoft Azure PowerShell: HanaOn cmdlets + +## Az.HanaOnAzure Cmdlets +### [Get-AzSapMonitor](Get-AzSapMonitor.md) +Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + +### [Get-AzSapMonitorProviderInstance](Get-AzSapMonitorProviderInstance.md) +Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +### [New-AzSapMonitor](New-AzSapMonitor.md) +Creates a SAP monitor for the specified subscription, resource group, and resource name. + +### [New-AzSapMonitorProviderInstance](New-AzSapMonitorProviderInstance.md) +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +### [Remove-AzSapMonitor](Remove-AzSapMonitor.md) +Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + +### [Remove-AzSapMonitorProviderInstance](Remove-AzSapMonitorProviderInstance.md) +Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +### [Update-AzSapMonitor](Update-AzSapMonitor.md) +Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + diff --git a/src/HanaOnAzure/help/Get-AzSapMonitor.md b/src/HanaOnAzure/help/Get-AzSapMonitor.md new file mode 100644 index 000000000000..cb18480c68b7 --- /dev/null +++ b/src/HanaOnAzure/help/Get-AzSapMonitor.md @@ -0,0 +1,194 @@ +--- +external help file: +Module Name: Az.HanaOnAzure +online version: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azsapmonitor +schema: 2.0.0 +--- + +# Get-AzSapMonitor + +## SYNOPSIS +Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + +## SYNTAX + +### List (Default) +``` +Get-AzSapMonitor [-SubscriptionId ] [-DefaultProfile ] [] +``` + +### Get +``` +Get-AzSapMonitor -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [] +``` + +### GetViaIdentity +``` +Get-AzSapMonitor -InputObject [-DefaultProfile ] [] +``` + +## DESCRIPTION +Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + +## EXAMPLES + +### Example 1: Get all SAP monitors under a subscription +```powershell +PS C:\> Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets SAP monitors under a subscription. + +### Example 2: Get a SAP monitor by name +```powershell +PS C:\> Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets a SAP monitor by name. + +### Example 3: Get a SAP monitor by object +```powershell +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 +PS C:\> Get-AzSapMonitor -InputObject $sap + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets a SAP monitor by object. + +### Example 4: Get a SAP monitor by pipeline +```powershell +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01'} | Get-AzSapMonitor + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command gets a SAP monitor by pipeline. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +Name of the SAP monitor resource. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: SapMonitorName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +Name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Subscription ID which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String[] +Parameter Sets: Get, List +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[Location ]`: The location of the deleted vault. + - `[OperationKind ]`: Name of the operation + - `[ProviderInstanceName ]`: Name of the provider instance. + - `[ResourceGroupName ]`: Name of the resource group. + - `[ResourceName ]`: The name of the identity resource. + - `[SapMonitorName ]`: Name of the SAP monitor resource. + - `[Scope ]`: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + - `[SubscriptionId ]`: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + - `[VaultName ]`: Name of the vault + +## RELATED LINKS + diff --git a/src/HanaOnAzure/help/Get-AzSapMonitorProviderInstance.md b/src/HanaOnAzure/help/Get-AzSapMonitorProviderInstance.md new file mode 100644 index 000000000000..8340b783a3a9 --- /dev/null +++ b/src/HanaOnAzure/help/Get-AzSapMonitorProviderInstance.md @@ -0,0 +1,211 @@ +--- +external help file: +Module Name: Az.HanaOnAzure +online version: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azsapmonitorproviderinstance +schema: 2.0.0 +--- + +# Get-AzSapMonitorProviderInstance + +## SYNOPSIS +Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +## SYNTAX + +### List (Default) +``` +Get-AzSapMonitorProviderInstance -ResourceGroupName -SapMonitorName + [-SubscriptionId ] [-DefaultProfile ] [] +``` + +### Get +``` +Get-AzSapMonitorProviderInstance -Name -ResourceGroupName -SapMonitorName + [-SubscriptionId ] [-DefaultProfile ] [] +``` + +### GetViaIdentity +``` +Get-AzSapMonitorProviderInstance -InputObject [-DefaultProfile ] + [] +``` + +## DESCRIPTION +Gets properties of a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +## EXAMPLES + +### Example 1: Get all instances under a SAP monitor +```powershell +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets all instances under a SAP monitor. + +### Example 2: Get an instances of SAP monitor by name +```powershell +PS C:\> Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets an instances of SAP monitor by name. + +### Example 3: Get an instances of SAP monitor by object +```powershell +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 +PS C:\> Get-AzSapMonitorProviderInstance -InputObject $sapIns + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets an instances of SAP monitor by object. + +### Example 4: Get an instances of SAP monitor by pipeline +```powershell +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/ps-spamonitor-t01/providerInstances/ps-sapmonitorins-t02"} | Get-AzSapMonitorProviderInstance + +Name Type +---- ---- +ps-sapmonitorins-t02 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command gets an instances of SAP monitor by pipeline. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +Name of the provider instance. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: ProviderInstanceName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +Name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SapMonitorName +Name of the SAP monitor resource. + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Subscription ID which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String[] +Parameter Sets: Get, List +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[Location ]`: The location of the deleted vault. + - `[OperationKind ]`: Name of the operation + - `[ProviderInstanceName ]`: Name of the provider instance. + - `[ResourceGroupName ]`: Name of the resource group. + - `[ResourceName ]`: The name of the identity resource. + - `[SapMonitorName ]`: Name of the SAP monitor resource. + - `[Scope ]`: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + - `[SubscriptionId ]`: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + - `[VaultName ]`: Name of the vault + +## RELATED LINKS + diff --git a/src/HanaOnAzure/help/New-AzSapMonitor.md b/src/HanaOnAzure/help/New-AzSapMonitor.md new file mode 100644 index 000000000000..0499019cb51d --- /dev/null +++ b/src/HanaOnAzure/help/New-AzSapMonitor.md @@ -0,0 +1,284 @@ +--- +external help file: +Module Name: Az.HanaOnAzure +online version: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azsapmonitor +schema: 2.0.0 +--- + +# New-AzSapMonitor + +## SYNOPSIS +Creates a SAP monitor for the specified subscription, resource group, and resource name. + +## SYNTAX + +``` +New-AzSapMonitor -Name -ResourceGroupName -Location [-SubscriptionId ] + [-EnableCustomerAnalytic] [-LogAnalyticsWorkspaceId ] [-LogAnalyticsWorkspaceResourceId ] + [-LogAnalyticsWorkspaceSharedKey ] [-MonitorSubnetResourceId ] [-Tag ] + [-DefaultProfile ] [-AsJob] [-NoWait] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Creates a SAP monitor for the specified subscription, resource group, and resource name. + +## EXAMPLES + +### Example 1: New SAP monitor +```powershell +PS C:\> $workspace = New-AzOperationalInsightsWorkspace -ResourceGroupName nancyc-hn1 -Name sapmonitor-test -Location westus2 -Sku "Standard" +PS C:\> $workspace = Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName nancyc-hn1 -Name sapmonitor-test +PS C:\> New-AzSapMonitor -Name ps-sapmonitor-t01 -ResourceGroupName nancyc-hn1 -Location westus2 -EnableCustomerAnalytic -MonitorSubnet "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin" -LogAnalyticsWorkspaceSharedKey $workspace.PrimarySharedKey -LogAnalyticsWorkspaceId $workspace.CustomerId -LogAnalyticsWorkspaceResourceId $workspace.ResourceId + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This command creates a SAP monitor. + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableCustomerAnalytic +The value indicating whether to send analytics to Microsoft + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Location +The geo-location where the resource lives + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LogAnalyticsWorkspaceId +The workspace ID of the log analytics workspace to be used for monitoring + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LogAnalyticsWorkspaceResourceId +The ARM ID of the Log Analytics Workspace that is used for monitoring + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LogAnalyticsWorkspaceSharedKey +The shared key of the log analytics workspace that is used for monitoring + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -MonitorSubnetResourceId +The subnet which the SAP monitor will be deployed in. +It should be the same subnet of HANA database. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Name of the SAP monitor resource. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: SapMonitorName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +Name of the resource group. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Subscription ID which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +Resource tags. + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + +## NOTES + +ALIASES + +## RELATED LINKS + diff --git a/src/HanaOnAzure/help/New-AzSapMonitorProviderInstance.md b/src/HanaOnAzure/help/New-AzSapMonitorProviderInstance.md new file mode 100644 index 000000000000..ba7b42ff971f --- /dev/null +++ b/src/HanaOnAzure/help/New-AzSapMonitorProviderInstance.md @@ -0,0 +1,349 @@ +--- +external help file: +Module Name: Az.HanaOnAzure +online version: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azsapmonitorproviderinstance +schema: 2.0.0 +--- + +# New-AzSapMonitorProviderInstance + +## SYNOPSIS +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +## SYNTAX + +### ByString (Default) +``` +New-AzSapMonitorProviderInstance -Name -ResourceGroupName -SapMonitorName + -HanaDatabaseName -HanaDatabasePassword -HanaDatabaseSqlPort + -HanaDatabaseUsername -HanaHostname -ProviderType [-SubscriptionId ] + [-Metadata ] [-DefaultProfile ] [-AsJob] [-NoWait] [-Confirm] [-WhatIf] + [] +``` + +### ByKeyVault +``` +New-AzSapMonitorProviderInstance -Name -ResourceGroupName -SapMonitorName + -HanaDatabaseName -HanaDatabasePasswordKeyVaultResourceId + -HanaDatabasePasswordSecretId -HanaDatabaseSqlPort -HanaDatabaseUsername + -HanaHostname -ProviderType [-SubscriptionId ] [-Metadata ] + [-DefaultProfile ] [-AsJob] [-NoWait] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +## EXAMPLES + +### Example 1: Create an instance of SAP monitor by string for HANA +```powershell +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -Name ps-sapmonitorins-t01 -SapMonitorName yemingmonitor -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command creates an instance of SAP monitor by string for HANA. + +### Example 2: Create an instance of SAP monitor by key vault for HANA +```powershell +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName sapMonitor-vayh7q-test -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId https://kv-9gosjc-test.vault.azure.net/secrets/hanaPassword/bf516d1dfcc144138e5cf55114f3344b -HanaDatabasePasswordKeyVaultResourceId /subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-8p50xe/providers/Microsoft.KeyVault/vaults/kv-9gosjc-test -Name sapins-kv-test + +Name Type +---- ---- +sapins-kv-test Microsoft.HanaOnAzure/sapMonitors/providerInstances +``` + +This command creates an instance of SAP monitor by key vault for HANA. + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HanaDatabaseName +The database name of SAP HANA instance. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: HanaDbName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HanaDatabasePassword +The password of the database of SAP HANA instance. + +```yaml +Type: System.Security.SecureString +Parameter Sets: ByString +Aliases: HanaDbPassword + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HanaDatabasePasswordKeyVaultResourceId +Resource ID of the Key Vault that contains the HANA credentials. + +```yaml +Type: System.String +Parameter Sets: ByKeyVault +Aliases: HanaDbPasswordKeyVaultId, KeyVaultId + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HanaDatabasePasswordSecretId +Secret identifier to the Key Vault secret that contains the HANA credentials. + +```yaml +Type: System.String +Parameter Sets: ByKeyVault +Aliases: HanaDbPasswordSecretId, SecretId + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HanaDatabaseSqlPort +The SQL port of the database of SAP HANA instance. + +```yaml +Type: System.Int32 +Parameter Sets: (All) +Aliases: HanaDbSqlPort + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HanaDatabaseUsername +The username of the database of SAP HANA instance. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: HanaDbUsername + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HanaHostname +The hostname of SAP HANA instance. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Metadata +A JSON string containing metadata of the provider instance. + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Name of the provider instance. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: ProviderInstanceName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProviderType +The type of provider instance. +Supported values are: "SapHana". + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +Name of the resource group. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SapMonitorName +Name of the SAP monitor resource. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Subscription ID which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance + +## NOTES + +ALIASES + +## RELATED LINKS + diff --git a/src/HanaOnAzure/help/Remove-AzSapMonitor.md b/src/HanaOnAzure/help/Remove-AzSapMonitor.md new file mode 100644 index 000000000000..95beeebc74fd --- /dev/null +++ b/src/HanaOnAzure/help/Remove-AzSapMonitor.md @@ -0,0 +1,237 @@ +--- +external help file: +Module Name: Az.HanaOnAzure +online version: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azsapmonitor +schema: 2.0.0 +--- + +# Remove-AzSapMonitor + +## SYNOPSIS +Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + +## SYNTAX + +### Delete (Default) +``` +Remove-AzSapMonitor -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [-AsJob] [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +### DeleteViaIdentity +``` +Remove-AzSapMonitor -InputObject [-DefaultProfile ] [-AsJob] [-NoWait] + [-PassThru] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + +## EXAMPLES + +### Example 1: Remove a SAP monitor by name +```powershell +PS C:\> Remove-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t02 + +``` + +This command removes a SAP monitor by name. + +### Example 2: Remove a SAP monitor by object +```powershell +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Remove-AzSapMonitor -InputObject $sap + +``` + +This command removes a SAP monitor by object. + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +Name of the SAP monitor resource. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: SapMonitorName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +Name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Subscription ID which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[Location ]`: The location of the deleted vault. + - `[OperationKind ]`: Name of the operation + - `[ProviderInstanceName ]`: Name of the provider instance. + - `[ResourceGroupName ]`: Name of the resource group. + - `[ResourceName ]`: The name of the identity resource. + - `[SapMonitorName ]`: Name of the SAP monitor resource. + - `[Scope ]`: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + - `[SubscriptionId ]`: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + - `[VaultName ]`: Name of the vault + +## RELATED LINKS + diff --git a/src/HanaOnAzure/help/Remove-AzSapMonitorProviderInstance.md b/src/HanaOnAzure/help/Remove-AzSapMonitorProviderInstance.md new file mode 100644 index 000000000000..633b6779ffeb --- /dev/null +++ b/src/HanaOnAzure/help/Remove-AzSapMonitorProviderInstance.md @@ -0,0 +1,253 @@ +--- +external help file: +Module Name: Az.HanaOnAzure +online version: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azsapmonitorproviderinstance +schema: 2.0.0 +--- + +# Remove-AzSapMonitorProviderInstance + +## SYNOPSIS +Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +## SYNTAX + +### Delete (Default) +``` +Remove-AzSapMonitorProviderInstance -Name -ResourceGroupName -SapMonitorName + [-SubscriptionId ] [-DefaultProfile ] [-AsJob] [-NoWait] [-PassThru] [-Confirm] [-WhatIf] + [] +``` + +### DeleteViaIdentity +``` +Remove-AzSapMonitorProviderInstance -InputObject [-DefaultProfile ] [-AsJob] + [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Deletes a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. + +## EXAMPLES + +### Example 1: Remove instance of SAP monitor by name +```powershell +PS C:\> Remove-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t02 + +``` + +This command removes instance of SAP monitor by name. + +### Example 2: Remove instance of SAP monitor by object +```powershell +PS C:\> $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName ps-spamonitor-t01 -Name ps-sapmonitorins-t01 +PS C:\> Remove-AzSapMonitorProviderInstance -InputObject $sapIns + +``` + +This command removes instance of SAP monitor by object. + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +Name of the provider instance. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: ProviderInstanceName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +Name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SapMonitorName +Name of the SAP monitor resource. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Subscription ID which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[Location ]`: The location of the deleted vault. + - `[OperationKind ]`: Name of the operation + - `[ProviderInstanceName ]`: Name of the provider instance. + - `[ResourceGroupName ]`: Name of the resource group. + - `[ResourceName ]`: The name of the identity resource. + - `[SapMonitorName ]`: Name of the SAP monitor resource. + - `[Scope ]`: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + - `[SubscriptionId ]`: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + - `[VaultName ]`: Name of the vault + +## RELATED LINKS + diff --git a/src/HanaOnAzure/help/Update-AzSapMonitor.md b/src/HanaOnAzure/help/Update-AzSapMonitor.md new file mode 100644 index 000000000000..162145c29258 --- /dev/null +++ b/src/HanaOnAzure/help/Update-AzSapMonitor.md @@ -0,0 +1,213 @@ +--- +external help file: +Module Name: Az.HanaOnAzure +online version: https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/update-azsapmonitor +schema: 2.0.0 +--- + +# Update-AzSapMonitor + +## SYNOPSIS +Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + +## SYNTAX + +### UpdateExpanded (Default) +``` +Update-AzSapMonitor -Name -ResourceGroupName [-SubscriptionId ] [-Tag ] + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +### UpdateViaIdentityExpanded +``` +Update-AzSapMonitor -InputObject [-Tag ] [-DefaultProfile ] + [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + +## EXAMPLES + +### Example 1: Update a SAP monitor by name +```powershell +PS C:\> Update-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-spamonitor-t01 -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-spamonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This commands updates a SAP monitor by name. + +### Example 2: Update a SAP monitor by object +```powershell +PS C:\> $sap = Get-AzSapMonitor -ResourceGroupName nancyc-hn1 -Name ps-sapmonitor-t01 +PS C:\> Update-AzSapMonitor -InputObject $sap -Tag @{'key'=1;'key2'=2; 'key3'=3} + +Location Name Type +-------- ---- ---- +westus2 ps-sapmonitor-t01 Microsoft.HanaOnAzure/sapMonitors +``` + +This commands updates a SAP monitor by object. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +Parameter Sets: UpdateViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +Name of the SAP monitor resource. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: SapMonitorName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +Name of the resource group. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Subscription ID which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +Tags field of the resource. + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.ISapMonitor + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[Location ]`: The location of the deleted vault. + - `[OperationKind ]`: Name of the operation + - `[ProviderInstanceName ]`: Name of the provider instance. + - `[ResourceGroupName ]`: Name of the resource group. + - `[ResourceName ]`: The name of the identity resource. + - `[SapMonitorName ]`: Name of the SAP monitor resource. + - `[Scope ]`: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + - `[SubscriptionId ]`: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + - `[VaultName ]`: Name of the vault + +## RELATED LINKS + diff --git a/src/HanaOnAzure/how-to.md b/src/HanaOnAzure/how-to.md new file mode 100644 index 000000000000..9dfe8de5700c --- /dev/null +++ b/src/HanaOnAzure/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.HanaOnAzure`. + +## Building `Az.HanaOnAzure` +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.HanaOnAzure` +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.HanaOnAzure` +To pack `Az.HanaOnAzure` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://docs.microsoft.com/en-us/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.HanaOnAzure`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.HanaOnAzure.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.HanaOnAzure.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.HanaOnAzure`. + - `-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.HanaOnAzure` 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/HanaOnAzure/internal/Az.HanaOnAzure.internal.psm1 b/src/HanaOnAzure/internal/Az.HanaOnAzure.internal.psm1 new file mode 100644 index 000000000000..23397ea94e76 --- /dev/null +++ b/src/HanaOnAzure/internal/Az.HanaOnAzure.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.HanaOnAzure.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.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/HanaOnAzure/internal/Get-AzUserAssignedIdentity.ps1 b/src/HanaOnAzure/internal/Get-AzUserAssignedIdentity.ps1 new file mode 100644 index 000000000000..ee6d2b7059e9 --- /dev/null +++ b/src/HanaOnAzure/internal/Get-AzUserAssignedIdentity.ps1 @@ -0,0 +1,175 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets the identity. +.Description +Gets the identity. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azuserassignedidentity +#> +function Get-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List1', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_Get'; + GetViaIdentity = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_GetViaIdentity'; + List = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_List'; + List1 = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/New-AzSapMonitorProviderInstance.ps1 b/src/HanaOnAzure/internal/New-AzSapMonitorProviderInstance.ps1 new file mode 100644 index 000000000000..9e16e56f404a --- /dev/null +++ b/src/HanaOnAzure/internal/New-AzSapMonitorProviderInstance.ps1 @@ -0,0 +1,185 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -Name ps-sapmonitorins-t01 -SapMonitorName yemingmonitor -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName sapMonitor-vayh7q-test -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId https://kv-9gosjc-test.vault.azure.net/secrets/hanaPassword/bf516d1dfcc144138e5cf55114f3344b -HanaDatabasePasswordKeyVaultResourceId /subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-8p50xe/providers/Microsoft.KeyVault/vaults/kv-9gosjc-test -Name sapins-kv-test + +Name Type +---- ---- +sapins-kv-test Microsoft.HanaOnAzure/sapMonitors/providerInstances + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azsapmonitorproviderinstance +#> +function New-AzSapMonitorProviderInstance { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # A JSON string containing metadata of the provider instance. + ${Metadata}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # A JSON string containing the properties of the provider instance. + ${ProviderInstanceProperty}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The type of provider instance. + ${ProviderType}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.HanaOnAzure.private\New-AzSapMonitorProviderInstance_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/New-AzUserAssignedIdentity.ps1 b/src/HanaOnAzure/internal/New-AzUserAssignedIdentity.ps1 new file mode 100644 index 000000000000..0e4117d6ef94 --- /dev/null +++ b/src/HanaOnAzure/internal/New-AzUserAssignedIdentity.ps1 @@ -0,0 +1,157 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create or update an identity in the specified subscription and resource group. +.Description +Create or update an identity in the specified subscription and resource group. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azuserassignedidentity +#> +function New-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.HanaOnAzure.private\New-AzUserAssignedIdentity_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/ProxyCmdletDefinitions.ps1 b/src/HanaOnAzure/internal/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..fa2328f8bb96 --- /dev/null +++ b/src/HanaOnAzure/internal/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,1205 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets the identity. +.Description +Gets the identity. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/get-azuserassignedidentity +#> +function Get-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List1', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_Get'; + GetViaIdentity = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_GetViaIdentity'; + List = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_List'; + List1 = 'Az.HanaOnAzure.private\Get-AzUserAssignedIdentity_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Description +Creates a provider instance for the specified subscription, resource group, SapMonitor name, and resource name. +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -Name ps-sapmonitorins-t01 -SapMonitorName yemingmonitor -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + +Name Type +---- ---- +ps-sapmonitorins-t01 Microsoft.HanaOnAzure/sapMonitors/providerInstances +.Example +PS C:\> New-AzSapMonitorProviderInstance -ResourceGroupName nancyc-hn1 -SapMonitorName sapMonitor-vayh7q-test -ProviderType SapHana -HanaHostname 'hdb1-0' -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId https://kv-9gosjc-test.vault.azure.net/secrets/hanaPassword/bf516d1dfcc144138e5cf55114f3344b -HanaDatabasePasswordKeyVaultResourceId /subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-8p50xe/providers/Microsoft.KeyVault/vaults/kv-9gosjc-test -Name sapins-kv-test + +Name Type +---- ---- +sapins-kv-test Microsoft.HanaOnAzure/sapMonitors/providerInstances + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azsapmonitorproviderinstance +#> +function New-AzSapMonitorProviderInstance { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20200207Preview.IProviderInstance])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('ProviderInstanceName')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the provider instance. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the SAP monitor resource. + ${SapMonitorName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # A JSON string containing metadata of the provider instance. + ${Metadata}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # A JSON string containing the properties of the provider instance. + ${ProviderInstanceProperty}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The type of provider instance. + ${ProviderType}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.HanaOnAzure.private\New-AzSapMonitorProviderInstance_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create or update an identity in the specified subscription and resource group. +.Description +Create or update an identity in the specified subscription and resource group. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/new-azuserassignedidentity +#> +function New-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.HanaOnAzure.private\New-AzUserAssignedIdentity_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes the identity. +.Description +Deletes the identity. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azuserassignedidentity +#> +function Remove-AzUserAssignedIdentity { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.HanaOnAzure.private\Remove-AzUserAssignedIdentity_Delete'; + DeleteViaIdentity = 'Az.HanaOnAzure.private\Remove-AzUserAssignedIdentity_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create or update an identity in the specified subscription and resource group. +.Description +Create or update an identity in the specified subscription and resource group. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/set-azuserassignedidentity +#> +function Set-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Set-AzUserAssignedIdentity_UpdateExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Update access policies in a key vault in the specified subscription. +.Description +Update access policies in a key vault in the specified subscription. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters +.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. + +ACCESSPOLICY : An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID. + ObjectId : The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault. The object ID must be unique for the list of access policies. + TenantId : The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + [ApplicationId ]: Application ID of the client making request on behalf of a principal + [PermissionCertificate ]: Permissions to certificates + [PermissionKey ]: Permissions to keys + [PermissionSecret ]: Permissions to secrets + [PermissionStorage ]: Permissions to storage accounts +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/set-azvaultaccesspolicy +#> +function Set-AzVaultAccessPolicy { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind])] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind] + # Name of the operation + ${OperationKind}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the Resource Group to which the vault belongs. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the vault + ${VaultName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]] + # An array of 0 to 16 identities that have access to the key vault. + # All identities in the array must use the same tenant ID as the key vault's tenant ID. + # To construct, see NOTES section for ACCESSPOLICY properties and create a hash table. + ${AccessPolicy}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Set-AzVaultAccessPolicy_UpdateExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Update an identity in the specified subscription and resource group. +.Description +Update an identity in the specified subscription and resource group. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/update-azuserassignedidentity +#> +function Update-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Update-AzUserAssignedIdentity_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.HanaOnAzure.private\Update-AzUserAssignedIdentity_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/Remove-AzUserAssignedIdentity.ps1 b/src/HanaOnAzure/internal/Remove-AzUserAssignedIdentity.ps1 new file mode 100644 index 000000000000..2635bac90c59 --- /dev/null +++ b/src/HanaOnAzure/internal/Remove-AzUserAssignedIdentity.ps1 @@ -0,0 +1,176 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes the identity. +.Description +Deletes the identity. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/remove-azuserassignedidentity +#> +function Remove-AzUserAssignedIdentity { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.HanaOnAzure.private\Remove-AzUserAssignedIdentity_Delete'; + DeleteViaIdentity = 'Az.HanaOnAzure.private\Remove-AzUserAssignedIdentity_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/Set-AzUserAssignedIdentity.ps1 b/src/HanaOnAzure/internal/Set-AzUserAssignedIdentity.ps1 new file mode 100644 index 000000000000..e3d5ee865372 --- /dev/null +++ b/src/HanaOnAzure/internal/Set-AzUserAssignedIdentity.ps1 @@ -0,0 +1,157 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create or update an identity in the specified subscription and resource group. +.Description +Create or update an identity in the specified subscription and resource group. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/set-azuserassignedidentity +#> +function Set-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api10.ITrackedResourceTags]))] + [System.Collections.Hashtable] + # Resource tags. + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Set-AzUserAssignedIdentity_UpdateExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/Set-AzVaultAccessPolicy.ps1 b/src/HanaOnAzure/internal/Set-AzVaultAccessPolicy.ps1 new file mode 100644 index 000000000000..c335b0dfe0cd --- /dev/null +++ b/src/HanaOnAzure/internal/Set-AzVaultAccessPolicy.ps1 @@ -0,0 +1,172 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Update access policies in a key vault in the specified subscription. +.Description +Update access policies in a key vault in the specified subscription. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters +.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. + +ACCESSPOLICY : An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID. + ObjectId : The object ID of a user, service principal or security group in the Azure Active Directory tenant for the vault. The object ID must be unique for the list of access policies. + TenantId : The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. + [ApplicationId ]: Application ID of the client making request on behalf of a principal + [PermissionCertificate ]: Permissions to certificates + [PermissionKey ]: Permissions to keys + [PermissionSecret ]: Permissions to secrets + [PermissionStorage ]: Permissions to storage accounts +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/set-azvaultaccesspolicy +#> +function Set-AzVaultAccessPolicy { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IVaultAccessPolicyParameters])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind])] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Support.AccessPolicyUpdateKind] + # Name of the operation + ${OperationKind}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the Resource Group to which the vault belongs. + ${ResourceGroupName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the vault + ${VaultName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20161001.IAccessPolicyEntry[]] + # An array of 0 to 16 identities that have access to the key vault. + # All identities in the array must use the same tenant ID as the key vault's tenant ID. + # To construct, see NOTES section for ACCESSPOLICY properties and create a hash table. + ${AccessPolicy}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Set-AzVaultAccessPolicy_UpdateExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/Update-AzUserAssignedIdentity.ps1 b/src/HanaOnAzure/internal/Update-AzUserAssignedIdentity.ps1 new file mode 100644 index 000000000000..1e9c6f7929f8 --- /dev/null +++ b/src/HanaOnAzure/internal/Update-AzUserAssignedIdentity.ps1 @@ -0,0 +1,183 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Update an identity in the specified subscription and resource group. +.Description +Update an identity in the specified subscription and resource group. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [Location ]: The location of the deleted vault. + [OperationKind ]: Name of the operation + [ProviderInstanceName ]: Name of the provider instance. + [ResourceGroupName ]: Name of the resource group. + [ResourceName ]: The name of the identity resource. + [SapMonitorName ]: Name of the SAP monitor resource. + [Scope ]: The resource provider scope of the resource. Parent resource being extended by Managed Identities. + [SubscriptionId ]: Subscription ID which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + [VaultName ]: Name of the vault +.Link +https://docs.microsoft.com/en-us/powershell/module/az.hanaonazure/update-azuserassignedidentity +#> +function Update-AzUserAssignedIdentity { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentity])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # Name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [System.String] + # The name of the identity resource. + ${ResourceName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Subscription ID which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.IHanaOnAzureIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [System.String] + # The geo-location where the resource lives + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Models.Api20181130.IIdentityUpdateTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.HanaOnAzure.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.HanaOnAzure.private\Update-AzUserAssignedIdentity_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.HanaOnAzure.private\Update-AzUserAssignedIdentity_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/HanaOnAzure/internal/readme.md b/src/HanaOnAzure/internal/readme.md new file mode 100644 index 000000000000..917398b691c5 --- /dev/null +++ b/src/HanaOnAzure/internal/readme.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.HanaOnAzure.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.HanaOnAzure`. Instead, this sub-module is imported by the `..\custom\Az.HanaOnAzure.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.HanaOnAzure.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.HanaOnAzure`. \ No newline at end of file diff --git a/src/HanaOnAzure/pack-module.ps1 b/src/HanaOnAzure/pack-module.ps1 new file mode 100644 index 000000000000..c22fad33d87b --- /dev/null +++ b/src/HanaOnAzure/pack-module.ps1 @@ -0,0 +1,16 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/HanaOnAzure/readme.md b/src/HanaOnAzure/readme.md new file mode 100644 index 000000000000..3c320067f1ca --- /dev/null +++ b/src/HanaOnAzure/readme.md @@ -0,0 +1,150 @@ + +# Az.HanaOnAzure +This directory contains the PowerShell module for the HanaOn service. + +--- +## Status +[![Az.HanaOnAzure](https://img.shields.io/powershellgallery/v/Az.HanaOnAzure.svg?style=flat-square&label=Az.HanaOnAzure "Az.HanaOnAzure")](https://www.powershellgallery.com/packages/Az.HanaOnAzure/) + +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 1.8.1 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.HanaOnAzure`, see [how-to.md](how-to.md). + + +--- +## Generation Requirements +Use of the beta version of `autorest.powershell` generator requires the following: +- [NodeJS LTS](https://nodejs.org) (10.15.x LTS preferred) + - **Note**: It *will not work* with Node < 10.x. Using 11.x builds may cause issues as they may introduce instability or breaking changes. +> If you want an easy way to install and update Node, [NVS - Node Version Switcher](../nodejs/installing-via-nvs.md) or [NVM - Node Version Manager](../nodejs/installing-via-nvm.md) is recommended. +- [AutoRest](https://aka.ms/autorest) v3 beta
`npm install -g autorest@beta`
  +- PowerShell 6.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g pwsh`
  +- .NET Core SDK 2.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g dotnet-sdk-2.2`
  + +## Run Generation +In this directory, run AutoRest: +> `autorest` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +``` yaml +require: + - $(this-folder)/../readme.azure.noprofile.md + - $(repo)/specification/hanaonazure/resource-manager/readme.md + +# For new RP, the version is 0.1.0 +module-version: 0.1.0 +# Normally, title is the service name +title: HanaOnAzure +# Autorest will remove "Azure" in the generated module, resulting "Az.HanaOn" +# A work-around is to specify "service-name", which is of higher priority when calc the module name +service-name: HanaOnAzure +subject-prefix: SapMonitor + +# If there are post APIs for some kinds of actions in the RP, you may need to +# uncomment following line to support viaIdentity for these post APIs +# identity-correction-for-post: true + +directive: + # Following is two common directive which are normally required in all the RPs + # 1. Remove the unexpanded parameter set + # 2. For New-* cmdlets, ViaIdentity is not required, so CreateViaIdentityExpanded is removed as well + - where: + variant: ^Create$|^CreateViaIdentity$|^CreateViaIdentityExpanded$|^Update$|^UpdateViaIdentity$ + remove: true + # Remove the set-* cmdlet, update-* is enough + - where: + verb: Set + # But do not remove set-* from key vault, that is needed + subject: ^SapMonitor$|^ProviderInstance$|^HanaInstance$ + remove: true + # Remove commands of Hana instance, which need to be reconsidered + - where: + subject: HanaInstance + remove: true + # Rename some parameters to follow powershell convention + - where: + parameter-name: LogAnalyticsWorkspaceArmId + set: + parameter-name: LogAnalyticsWorkspaceResourceId + - where: + parameter-name: MonitorSubnet + set: + parameter-name: MonitorSubnetResourceId + - where: + parameter-name: PropertiesType + set: + parameter-name: ProviderType + + # Update some parameter description + - where: + parameter-name: MonitorSubnetResourceId + subject: SapMonitor + set: + parameter-description: The subnet which the SAP monitor will be deployed in. It should be the same subnet of HANA database. + + # Make location required + # Fixme: when service team makes the change, remove this line + - from: swagger-document + where: $.definitions.TrackedResource + transform: $['required'] = ['location'] + # Hide New-*ProviderInstance for customization + - where: + verb: New + subject: ProviderInstance + hide: true + + # Table format + - where: + model-name: ProviderInstance + set: + format-table: + properties: + - Name + - ProviderType + labels: + ProviderType: Provider Type + - where: + model-name: SapMonitor + set: + format-table: + properties: + - Name + - Location +``` + +``` yaml +# HELPERS +# ManagedIdentity and KeyVault is required when creating provider instance +require: + - $(this-folder)/../helpers/ManagedIdentity/readme.noprofile.md + - $(this-folder)/../helpers/KeyVault/readme.noprofile.md + +directive: + # remove unneeded cmdlets + - where: + subject: ^VaultDeleted$|^Vault$|^VaultNameAvailability$ + remove: true + - where: + subject: ^SystemAssignedIdentity$ + remove: true +``` diff --git a/src/HanaOnAzure/run-module.ps1 b/src/HanaOnAzure/run-module.ps1 new file mode 100644 index 000000000000..6fd42e67efa5 --- /dev/null +++ b/src/HanaOnAzure/run-module.ps1 @@ -0,0 +1,59 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.HanaOnAzure.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/HanaOnAzure/test-module.ps1 b/src/HanaOnAzure/test-module.ps1 new file mode 100644 index 000000000000..c9efe34d11dd --- /dev/null +++ b/src/HanaOnAzure/test-module.ps1 @@ -0,0 +1,68 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Live, [switch]$Record, [switch]$Playback) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts:$false -Pester -Resources:$requireResourceModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) { + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.HanaOnAzure.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +if($Live) { + $TestMode = 'live' +} +if($Record) { + $TestMode = 'record' +} +try { + if ($TestMode -ne 'playback') { + setupEnv + } + $testFolder = Join-Path $PSScriptRoot 'test' + Invoke-Pester -Script @{ Path = $testFolder } -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") +} +Finally +{ + if ($TestMode -ne 'playback') { + cleanupEnv + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/HanaOnAzure/test/Get-AzSapMonitor.Recording.json b/src/HanaOnAzure/test/Get-AzSapMonitor.Recording.json new file mode 100644 index 000000000000..58d856f0b63f --- /dev/null +++ b/src/HanaOnAzure/test/Get-AzSapMonitor.Recording.json @@ -0,0 +1,162 @@ +{ + "Get-AzSapMonitor+[NoContext]+List+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/sapMonitors?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/sapMonitors?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1" ], + "x-ms-client-request-id": [ "ca871d24-a132-4f36-9156-02bf4d32a36a" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T060345Z:52c65fca-c329-476e-bf62-6bf0a568b9e2" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11996" ], + "x-ms-correlation-request-id": [ "52c65fca-c329-476e-bf62-6bf0a568b9e2" ], + "x-ms-request-id": [ "edc0a00d-1d96-431f-b9c4-75123296207e" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:03:45 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "5364" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"value\": [\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-j1sm2o-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-j1sm2o-test\",\n \"tags\": {\n \"key\": \"1\",\n \"key2\": \"2\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-48537d0733dfc9\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-jeiysz/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-wohtnd\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-rnwz0m-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-rnwz0m-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-9cd4a794632527\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-o3udez/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-1jx26e\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-vayh7q-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-vayh7q-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-9eec93615bc403\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-dj6nwo/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-tbmy5e\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/yemingmonitor5\",\n \"location\": \"westus2\",\n \"name\": \"yemingmonitor5\",\n \"tags\": {\n \"a\": \"b\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Deleting\",\n \"managedResourceGroupName\": \"sapmon-rg-7dc200167f3865\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.OperationalInsights/workspaces/yeminglaw\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-db-a\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/yemingmonitortest\",\n \"location\": \"westus2\",\n \"name\": \"yemingmonitortest\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-31fb7355419438\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.OperationalInsights/workspaces/yeminglaw\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }\n ]\n }" + } + }, + "Get-AzSapMonitor+[NoContext]+Get+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "2" ], + "x-ms-client-request-id": [ "da28bd37-169f-44e3-a62d-653415e7501d" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T060346Z:2735fa2c-dedf-48a0-903d-ea5fb84d0625" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11995" ], + "x-ms-correlation-request-id": [ "2735fa2c-dedf-48a0-903d-ea5fb84d0625" ], + "x-ms-request-id": [ "bdacd02e-25e0-499d-8cdb-93f747303027" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:03:46 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "863" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "Get-AzSapMonitor+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "3" ], + "x-ms-client-request-id": [ "1a1c2b7d-a435-45da-bacc-66d961767bf2" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T060346Z:4949eb8f-7b51-4aeb-9e07-aa03bc1e2e5a" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11994" ], + "x-ms-correlation-request-id": [ "4949eb8f-7b51-4aeb-9e07-aa03bc1e2e5a" ], + "x-ms-request-id": [ "fe3d916a-8d89-4f9d-99e9-4d52e49855ca" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:03:46 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "863" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "Get-AzSapMonitor+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "4" ], + "x-ms-client-request-id": [ "07fa7177-6630-42d3-8414-dc9dad81df7e" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_GetViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T060346Z:a5fa4a59-0bc9-48bd-aef8-e48c451f9c42" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11993" ], + "x-ms-correlation-request-id": [ "a5fa4a59-0bc9-48bd-aef8-e48c451f9c42" ], + "x-ms-request-id": [ "e8fab2f0-6d2d-4e47-a2da-605cc601736a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:03:46 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "863" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/Get-AzSapMonitor.Tests.ps1 b/src/HanaOnAzure/test/Get-AzSapMonitor.Tests.ps1 new file mode 100644 index 000000000000..0079d0c1900b --- /dev/null +++ b/src/HanaOnAzure/test/Get-AzSapMonitor.Tests.ps1 @@ -0,0 +1,30 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzSapMonitor.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-AzSapMonitor' { + It 'List' { + $sapMonitorList = Get-AzSapMonitor + $sapMonitorList.Count | Should -BeGreaterOrEqual 1 + } + + It 'Get' { + $sapMonitor = Get-AzSapMonitor -ResourceGroupName $env.resourceGroup -Name $env.sapMonitor01 + $sapMonitor.Name | Should -Be $env.sapMonitor01 + } + + It 'GetViaIdentity' { + $sapMonitor = Get-AzSapMonitor -ResourceGroupName $env.resourceGroup -Name $env.sapMonitor01 + $sapMonitor = Get-AzSapMonitor -InputObject $sapMonitor + $sapMonitor.Name | Should -Be $env.sapMonitor01 + } +} diff --git a/src/HanaOnAzure/test/Get-AzSapMonitorProviderInstance.Recording.json b/src/HanaOnAzure/test/Get-AzSapMonitorProviderInstance.Recording.json new file mode 100644 index 000000000000..c5ae68cad94e --- /dev/null +++ b/src/HanaOnAzure/test/Get-AzSapMonitorProviderInstance.Recording.json @@ -0,0 +1,162 @@ +{ + "Get-AzSapMonitorProviderInstance+[NoContext]+List+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1" ], + "x-ms-client-request-id": [ "4797e415-cb5e-414b-a56b-8f2b92297142" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061432Z:96ac3ea2-7e01-4795-acc0-80789915f604" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11998" ], + "x-ms-correlation-request-id": [ "96ac3ea2-7e01-4795-acc0-80789915f604" ], + "x-ms-request-id": [ "d419b2d4-d85a-47d8-a758-1eed7d800b6a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:14:32 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1332" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"value\": [\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-bukeg9\",\n \"location\": \"\",\n \"name\": \"sapInstance-bukeg9\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\",\\\"hanaDbPasswordKeyVaultUrl\\\":\\\"https://kv-7zeudq-test.vault.azure.net:443/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Failed\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k\",\n \"location\": \"\",\n \"name\": \"sapInstance-p6zm1k\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Succeeded\"\n }\n }\n ]\n }" + } + }, + "Get-AzSapMonitorProviderInstance+[NoContext]+Get+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "2" ], + "x-ms-client-request-id": [ "973171f7-9818-4d3f-bf23-903d73445ebf" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061433Z:7ddfe1ee-2cb1-458d-af32-6ab150a00a5b" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11997" ], + "x-ms-correlation-request-id": [ "7ddfe1ee-2cb1-458d-af32-6ab150a00a5b" ], + "x-ms-request-id": [ "803dd398-f42c-4357-9a6b-8f44faf80c9a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:14:32 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "563" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k\",\n \"location\": \"\",\n \"name\": \"sapInstance-p6zm1k\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Succeeded\"\n }\n }" + } + }, + "Get-AzSapMonitorProviderInstance+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "3" ], + "x-ms-client-request-id": [ "827d4b87-0da6-4a40-a545-16b77d055657" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061433Z:07b3d075-aa89-47bb-b628-0147307cd5e0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11996" ], + "x-ms-correlation-request-id": [ "07b3d075-aa89-47bb-b628-0147307cd5e0" ], + "x-ms-request-id": [ "67ed88f5-d750-4251-9bfe-851619274209" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:14:33 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "563" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k\",\n \"location\": \"\",\n \"name\": \"sapInstance-p6zm1k\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Succeeded\"\n }\n }" + } + }, + "Get-AzSapMonitorProviderInstance+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "4" ], + "x-ms-client-request-id": [ "a4fc032d-2178-46b8-921e-5c12720fe644" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_GetViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061433Z:fad6cae6-5c80-448b-9e07-e9358e0b0098" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11995" ], + "x-ms-correlation-request-id": [ "fad6cae6-5c80-448b-9e07-e9358e0b0098" ], + "x-ms-request-id": [ "d3a366bc-21db-4c7e-9026-8976fdfa0698" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:14:33 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "563" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k\",\n \"location\": \"\",\n \"name\": \"sapInstance-p6zm1k\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Succeeded\"\n }\n }" + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/Get-AzSapMonitorProviderInstance.Tests.ps1 b/src/HanaOnAzure/test/Get-AzSapMonitorProviderInstance.Tests.ps1 new file mode 100644 index 000000000000..febe6092cf43 --- /dev/null +++ b/src/HanaOnAzure/test/Get-AzSapMonitorProviderInstance.Tests.ps1 @@ -0,0 +1,30 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzSapMonitorProviderInstance.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-AzSapMonitorProviderInstance' { + It 'List' { + $sapInsList = Get-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -SapMonitorName $env.sapMonitor01 + $sapInsList.Count | Should -Be 2 + } + + It 'Get' { + $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -SapMonitorName $env.sapMonitor01 -Name $env.sapIns01 + $sapIns.Name | Should -Be $env.sapIns01 + } + + It 'GetViaIdentity' { + $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -SapMonitorName $env.sapMonitor01 -Name $env.sapIns01 + $sapIns = Get-AzSapMonitorProviderInstance -InputObject $sapIns + $sapIns.Name | Should -Be $env.sapIns01 + } +} diff --git a/src/HanaOnAzure/test/New-AzSapMonitor.Recording.json b/src/HanaOnAzure/test/New-AzSapMonitor.Recording.json new file mode 100644 index 000000000000..639d6e1337f1 --- /dev/null +++ b/src/HanaOnAzure/test/New-AzSapMonitor.Recording.json @@ -0,0 +1,517 @@ +{ + "New-AzSapMonitor+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview", + "Content": "{\n \"location\": \"westus2\",\n \"properties\": {\n \"enableCustomerAnalytics\": true,\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt\",\n \"logAnalyticsWorkspaceId\": \"\",\n \"logAnalyticsWorkspaceSharedKey\": \"Qf/scKlrNjkyMot3WIlWvw1/p3c1+1uRtu5fRI0ihpws92OqawKurEYuODmGlkfb81gfW03zTITzOF1QARpF6w==\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "634" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1199" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "6d0a8770-ea3d-495f-8a41-fe67312cc0a3" ], + "x-ms-request-id": [ "45cbdd2c-56af-4eb4-bd5d-a49da76eff4a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061627Z:6d0a8770-ea3d-495f-8a41-fe67312cc0a3" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:16:26 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "957" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-wrlm5y-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Accepted\",\n \"managedResourceGroupName\": \"\",\n \"enableCustomerAnalytics\": true,\n \"sapMonitorCollectorVersion\": \"\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt\",\n \"logAnalyticsWorkspaceSharedKey\": \"Qf/scKlrNjkyMot3WIlWvw1/p3c1+1uRtu5fRI0ihpws92OqawKurEYuODmGlkfb81gfW03zTITzOF1QARpF6w==\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11994" ], + "x-ms-correlation-request-id": [ "fd81e0ec-8481-4df2-8e6e-2c763ffd970c" ], + "x-ms-request-id": [ "f684f72c-a484-4b4b-a5f2-1fc04211c5fb" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061658Z:fd81e0ec-8481-4df2-8e6e-2c763ffd970c" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:16:58 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11993" ], + "x-ms-correlation-request-id": [ "7cab45fd-8393-492f-a7a5-997e460916b2" ], + "x-ms-request-id": [ "8f50fa30-8353-4439-a46f-c26c05778f74" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061728Z:7cab45fd-8393-492f-a7a5-997e460916b2" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:17:28 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11992" ], + "x-ms-correlation-request-id": [ "f863073f-b872-4baa-8afc-f263ac7597f7" ], + "x-ms-request-id": [ "70ce1cd5-28e0-4e09-b7f1-5e5aae0dc807" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061758Z:f863073f-b872-4baa-8afc-f263ac7597f7" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:17:58 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11991" ], + "x-ms-correlation-request-id": [ "60ebc708-a7f6-4d30-9dca-a39ecf181e82" ], + "x-ms-request-id": [ "0a2ee55f-3479-46cd-9153-a73677f5f336" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061829Z:60ebc708-a7f6-4d30-9dca-a39ecf181e82" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:18:28 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+6": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11990" ], + "x-ms-correlation-request-id": [ "638f0c40-ba33-4304-bd8b-516a61407ad1" ], + "x-ms-request-id": [ "fc8c2905-d0bb-4250-bfdc-d88e2d7074f3" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061859Z:638f0c40-ba33-4304-bd8b-516a61407ad1" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:18:59 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+7": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11989" ], + "x-ms-correlation-request-id": [ "56ea6a30-5406-4896-90ec-b8279c7879ad" ], + "x-ms-request-id": [ "81d16a96-3e76-4c57-8046-fb3ced6c5cec" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T061929Z:56ea6a30-5406-4896-90ec-b8279c7879ad" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:19:29 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+8": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11988" ], + "x-ms-correlation-request-id": [ "bdc68240-1e31-41e5-8a81-bc2a34ab6e3a" ], + "x-ms-request-id": [ "e3fe7f22-213a-47e1-b35c-305dbd63b404" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T062000Z:bdc68240-1e31-41e5-8a81-bc2a34ab6e3a" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:19:59 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+9": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11987" ], + "x-ms-correlation-request-id": [ "2b27c07a-7236-4156-82c7-9825b8484218" ], + "x-ms-request-id": [ "88d0c120-6ffa-486b-831c-ddf921e26d7f" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T062030Z:2b27c07a-7236-4156-82c7-9825b8484218" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:20:30 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+10": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11986" ], + "x-ms-correlation-request-id": [ "692dfa7d-5461-45ed-8042-647a98aea1e2" ], + "x-ms-request-id": [ "389b5643-35aa-4b57-8c09-0e1ece549ca9" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T062100Z:692dfa7d-5461-45ed-8042-647a98aea1e2" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:21:00 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+11": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11985" ], + "x-ms-correlation-request-id": [ "87504b41-4a66-4274-bbdd-8b420d3c1794" ], + "x-ms-request-id": [ "bc4a119a-d3ab-4f83-8b5a-c2481b75741e" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T062131Z:87504b41-4a66-4274-bbdd-8b420d3c1794" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:21:30 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview+12": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/45cbdd2c-56af-4eb4-bd5d-a49da76eff4a?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11984" ], + "x-ms-correlation-request-id": [ "33a24fea-0887-4522-b5bf-bebad3c69059" ], + "x-ms-request-id": [ "a36db8c3-5a28-435b-96ef-904046be7084" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T062202Z:33a24fea-0887-4522-b5bf-bebad3c69059" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:22:01 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"45cbdd2c-56af-4eb4-bd5d-a49da76eff4a\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T06:16:26.2984518Z\",\n \"endTime\": \"2020-07-06T06:21:34.3606846Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitor+[NoContext]+CreateExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview+13": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], + "x-ms-client-request-id": [ "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b", "eb67f65f-b48c-418e-9087-6819ad2a8b5b" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T062202Z:8a869c6b-b7ce-4ce4-8381-2be2e9cda56a" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11983" ], + "x-ms-correlation-request-id": [ "8a869c6b-b7ce-4ce4-8381-2be2e9cda56a" ], + "x-ms-request-id": [ "736bc90b-69c8-4f25-ab16-4a447c2b35a5" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:22:02 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "863" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-wrlm5y-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-755d7b77729881\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/New-AzSapMonitor.Tests.ps1 b/src/HanaOnAzure/test/New-AzSapMonitor.Tests.ps1 new file mode 100644 index 000000000000..3d8eb653c45f --- /dev/null +++ b/src/HanaOnAzure/test/New-AzSapMonitor.Tests.ps1 @@ -0,0 +1,24 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzSapMonitor.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzSapMonitor' { + It 'CreateExpanded' { + $sapMonitor = New-AzSapMonitor -Name $env.sapMonitor02 -ResourceGroupName $env.resourceGroup -Location $env.location -EnableCustomerAnalytic ` + -MonitorSubnet $env.MonitorSubnet ` + -LogAnalyticsWorkspaceSharedKey $env.workspace02Key ` + -LogAnalyticsWorkspaceId $env.workspace02Id ` + -LogAnalyticsWorkspaceResourceId $env.workspaceResourceId02 + + $sapMonitor.ProvisioningState | Should -Be 'Succeeded' + } +} diff --git a/src/HanaOnAzure/test/New-AzSapMonitorProviderInstance.Recording.json b/src/HanaOnAzure/test/New-AzSapMonitorProviderInstance.Recording.json new file mode 100644 index 000000000000..efc388bfcaea --- /dev/null +++ b/src/HanaOnAzure/test/New-AzSapMonitorProviderInstance.Recording.json @@ -0,0 +1,548 @@ +{ + "New-AzSapMonitorProviderInstance+[NoContext]+CreateExpandedByString+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-ywnfxq?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-ywnfxq?api-version=2020-02-07-preview", + "Content": "{\n \"properties\": {\n \"type\": \"SapHana\",\n \"metadata\": \"null\",\n \"properties\": \"{\\n \\\"hanaHostname\\\": \\\"hdb1-0\\\",\\n \\\"hanaDbName\\\": \\\"SYSTEMDB\\\",\\n \\\"hanaDbPassword\\\": \\\"Manager1\\\",\\n \\\"hanaDbUsername\\\": \\\"SYSTEM\\\",\\n \\\"hanaDbSqlPort\\\": 30015\\n}\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "263" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1197" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "d19e97db-8c48-40ef-9612-485d29272a39" ], + "x-ms-request-id": [ "afefbee9-085a-435e-8d01-1a31c3db76a5" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064506Z:d19e97db-8c48-40ef-9612-485d29272a39" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:45:06 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "562" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-ywnfxq\",\n \"location\": \"\",\n \"name\": \"sapInstance-ywnfxq\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Accepted\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+CreateExpandedByString+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2" ], + "x-ms-client-request-id": [ "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11991" ], + "x-ms-correlation-request-id": [ "a764e8ac-88b7-41d6-8901-b0efb8ed1b7b" ], + "x-ms-request-id": [ "08fee32f-1851-44cb-913a-f0c14d63e18d" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064537Z:a764e8ac-88b7-41d6-8901-b0efb8ed1b7b" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:45:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"afefbee9-085a-435e-8d01-1a31c3db76a5\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:45:06.7623378Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+CreateExpandedByString+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2017-11-03-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3" ], + "x-ms-client-request-id": [ "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11990" ], + "x-ms-correlation-request-id": [ "951ebe72-7eb6-4f85-ad29-d1d72a48c4be" ], + "x-ms-request-id": [ "cdcfdbd9-80fb-4ae3-a718-5eaf471bb818" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064607Z:951ebe72-7eb6-4f85-ad29-d1d72a48c4be" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:46:07 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"afefbee9-085a-435e-8d01-1a31c3db76a5\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:45:06.7623378Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+CreateExpandedByString+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2017-11-03-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/afefbee9-085a-435e-8d01-1a31c3db76a5?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4" ], + "x-ms-client-request-id": [ "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11989" ], + "x-ms-correlation-request-id": [ "6a01311e-a145-4e81-9a73-4bfee6bb34eb" ], + "x-ms-request-id": [ "321ed2c7-3fd9-4d4d-bfe4-32a6adbcb224" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064637Z:6a01311e-a145-4e81-9a73-4bfee6bb34eb" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:46:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"afefbee9-085a-435e-8d01-1a31c3db76a5\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T06:45:06.7623378Z\",\n \"endTime\": \"2020-07-06T06:46:07.6155649Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+CreateExpandedByString+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-ywnfxq?api-version=2020-02-07-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-ywnfxq?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5" ], + "x-ms-client-request-id": [ "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10", "5e4bf828-c889-471b-9936-5b6c96242e10" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064638Z:bcc55acd-bfdd-4f41-82b1-8232c4a7ec95" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11988" ], + "x-ms-correlation-request-id": [ "bcc55acd-bfdd-4f41-82b1-8232c4a7ec95" ], + "x-ms-request-id": [ "e5edad7d-44af-441e-b3a4-14d3a376fba0" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:46:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "563" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-ywnfxq\",\n \"location\": \"\",\n \"name\": \"sapInstance-ywnfxq\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Succeeded\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "6" ], + "x-ms-client-request-id": [ "2d3a8451-59cb-443c-8e83-063aa5b71ded" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064638Z:a73c2757-5277-4920-8be6-05a445b54172" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11987" ], + "x-ms-correlation-request-id": [ "a73c2757-5277-4920-8be6-05a445b54172" ], + "x-ms-request-id": [ "82fd40df-2cf0-49df-8bde-1d00b0f133ec" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:46:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "863" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-wrlm5y-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-755d7b77729881\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/sapmon-rg-755d7b77729881/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sapmon-msi-755d7b77729881?api-version=2018-11-30+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/sapmon-rg-755d7b77729881/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sapmon-msi-755d7b77729881?api-version=2018-11-30", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "7" ], + "x-ms-client-request-id": [ "0a0c8f70-101f-4df5-afe3-7b10a639b4d9" ], + "CommandName": [ "Az.HanaOnAzure.internal\\Get-AzUserAssignedIdentity" ], + "FullCommandName": [ "Get-AzUserAssignedIdentity_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "Microsoft-HTTPAPI/2.0" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11986" ], + "x-ms-request-id": [ "0df93bdd-1b06-4dbb-86a6-959aaca27663" ], + "x-ms-correlation-request-id": [ "0df93bdd-1b06-4dbb-86a6-959aaca27663" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064640Z:0df93bdd-1b06-4dbb-86a6-959aaca27663" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:46:39 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "504" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/sapmon-rg-755d7b77729881/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sapmon-msi-755d7b77729881\",\"name\":\"sapmon-msi-755d7b77729881\",\"type\":\"Microsoft.ManagedIdentity/userAssignedIdentities\",\"location\":\"westus2\",\"tags\":{\"SapMonId\":\"755d7b77729881\"},\"properties\":{\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"principalId\":\"f1c401e7-6382-4fec-bc03-b121212e1ed1\",\"clientId\":\"a4b2ca5f-f66d-4d66-8c55-0c5b0b312e09\"}}" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-r3ox95/providers/Microsoft.KeyVault/vaults/kv-7zeudq-test/accessPolicies/add?api-version=2016-10-01+3": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-r3ox95/providers/Microsoft.KeyVault/vaults/kv-7zeudq-test/accessPolicies/add?api-version=2016-10-01", + "Content": "{\n \"properties\": {\n \"accessPolicies\": [\n {\n \"permissions\": {\n \"secrets\": [ \"get\" ]\n },\n \"objectId\": \"f1c401e7-6382-4fec-bc03-b121212e1ed1\",\n \"tenantId\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\"\n }\n ]\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "257" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-keyvault-service-version": [ "1.1.0.283" ], + "x-ms-request-id": [ "18a80d14-b67b-483d-b68d-4f8b2c3ea3f1" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0" ], + "X-AspNet-Version": [ "4.0.30319" ], + "X-Powered-By": [ "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1196" ], + "x-ms-correlation-request-id": [ "9110b3bf-2761-479c-8ece-919aaba2bbcd" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064642Z:9110b3bf-2761-479c-8ece-919aaba2bbcd" ], + "Date": [ "Mon, 06 Jul 2020 06:46:41 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "387" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-r3ox95/providers/Microsoft.KeyVault/vaults/kv-7zeudq-test/accessPolicies/\",\"type\":\"Microsoft.KeyVault/vaults/accessPolicies\",\"properties\":{\"accessPolicies\":[{\"tenantId\":\"72f988bf-86f1-41af-91ab-2d7cd011db47\",\"objectId\":\"f1c401e7-6382-4fec-bc03-b121212e1ed1\",\"permissions\":{\"secrets\":[\"get\"]}}]}}" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc?api-version=2020-02-07-preview+4": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc?api-version=2020-02-07-preview", + "Content": "{\n \"properties\": {\n \"type\": \"SapHana\",\n \"metadata\": \"null\",\n \"properties\": \"{\\n \\\"keyVaultCredentialsMsiClientID\\\": \\\"a4b2ca5f-f66d-4d66-8c55-0c5b0b312e09\\\",\\n \\\"hanaDbSqlPort\\\": 30015,\\n \\\"hanaDbUsername\\\": \\\"SYSTEM\\\",\\n \\\"hanaDbName\\\": \\\"SYSTEMDB\\\",\\n \\\"hanaHostname\\\": \\\"hdb1-0\\\",\\n \\\"hanaDbPasswordKeyVaultUrl\\\": \\\"https://kv-7zeudq-test.vault.azure.net/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2\\\",\\n \\\"keyVaultId\\\": \\\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-r3ox95/providers/Microsoft.KeyVault/vaults/kv-7zeudq-test\\\"\\n}\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "606" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1195" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "f099921a-dc51-4162-a69e-4c18fc3852c4" ], + "x-ms-request-id": [ "48434e6e-8173-4cd8-949c-52153282ef65" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064643Z:f099921a-dc51-4162-a69e-4c18fc3852c4" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:46:42 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "689" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc\",\n \"location\": \"\",\n \"name\": \"sapInstance-kopigc\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\",\\\"hanaDbPasswordKeyVaultUrl\\\":\\\"https://kv-7zeudq-test.vault.azure.net/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Accepted\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2020-02-07-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "9", "10" ], + "x-ms-client-request-id": [ "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "", "" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11985" ], + "x-ms-correlation-request-id": [ "094e4bcf-a3f5-48f2-951c-f8e306c68e4b" ], + "x-ms-request-id": [ "bc6810a7-a838-49e4-8a39-7204823e26a2" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064713Z:094e4bcf-a3f5-48f2-951c-f8e306c68e4b" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:47:13 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"48434e6e-8173-4cd8-949c-52153282ef65\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:46:43.1223718Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2017-11-03-preview+6": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "9", "10", "11" ], + "x-ms-client-request-id": [ "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "", "", "" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11984" ], + "x-ms-correlation-request-id": [ "9e2c5df4-264b-4cd4-9d6a-e805a62eae65" ], + "x-ms-request-id": [ "715c8ddf-6e84-4335-afec-13bf4a33f9ab" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064743Z:9e2c5df4-264b-4cd4-9d6a-e805a62eae65" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:47:43 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"48434e6e-8173-4cd8-949c-52153282ef65\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:46:43.1223718Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2017-11-03-preview+7": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/48434e6e-8173-4cd8-949c-52153282ef65?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "9", "10", "11", "12" ], + "x-ms-client-request-id": [ "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "", "", "", "" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11983" ], + "x-ms-correlation-request-id": [ "73709bf8-3f5b-47b5-ac77-a8db2ec782a5" ], + "x-ms-request-id": [ "50a8ed56-eaff-4147-87d1-d546064a42cf" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064814Z:73709bf8-3f5b-47b5-ac77-a8db2ec782a5" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:48:13 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"48434e6e-8173-4cd8-949c-52153282ef65\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T06:46:43.1223718Z\",\n \"endTime\": \"2020-07-06T06:47:44.0060582Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc?api-version=2020-02-07-preview+8": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "9", "10", "11", "12", "13" ], + "x-ms-client-request-id": [ "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab", "2fafbe1d-69a0-4134-b3a4-1252eb3349ab" ], + "CommandName": [ "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance", "Az.HanaOnAzure.internal\\New-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded", "New-AzSapMonitorProviderInstance_CreateExpanded" ], + "ParameterSetName": [ "", "", "", "", "" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064814Z:bcc944f0-c0cf-4452-b6a4-8c5e64603247" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11982" ], + "x-ms-correlation-request-id": [ "bcc944f0-c0cf-4452-b6a4-8c5e64603247" ], + "x-ms-request-id": [ "f3deccdf-b138-4ecf-9e43-d347b9c5c707" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:48:13 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "690" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc\",\n \"location\": \"\",\n \"name\": \"sapInstance-kopigc\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\",\\\"hanaDbPasswordKeyVaultUrl\\\":\\\"https://kv-7zeudq-test.vault.azure.net/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Succeeded\"\n }\n }" + } + }, + "New-AzSapMonitorProviderInstance+[NoContext]+ByKeyVault+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc?api-version=2020-02-07-preview+9": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "14" ], + "x-ms-client-request-id": [ "d8f0689d-bf07-440a-9ea8-8fa81779badb" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064814Z:cea467d4-9675-46c0-84d7-d64a6e7537a4" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11981" ], + "x-ms-correlation-request-id": [ "cea467d4-9675-46c0-84d7-d64a6e7537a4" ], + "x-ms-request-id": [ "b7e7fcaa-4730-43d3-af9f-1d832bff265c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:48:13 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "690" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test/providerInstances/sapInstance-kopigc\",\n \"location\": \"\",\n \"name\": \"sapInstance-kopigc\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\",\\\"hanaDbPasswordKeyVaultUrl\\\":\\\"https://kv-7zeudq-test.vault.azure.net/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Succeeded\"\n }\n }" + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/New-AzSapMonitorProviderInstance.Tests.ps1 b/src/HanaOnAzure/test/New-AzSapMonitorProviderInstance.Tests.ps1 new file mode 100644 index 000000000000..f53bb8f95161 --- /dev/null +++ b/src/HanaOnAzure/test/New-AzSapMonitorProviderInstance.Tests.ps1 @@ -0,0 +1,28 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzSapMonitorProviderInstance.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzSapMonitorProviderInstance' { + It 'CreateExpandedByString' { + $hostName = 'hdb1-0' + #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")] + $sapIns = New-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -Name $env.sapIns03 -SapMonitorName $env.sapMonitor02 -ProviderType SapHana -HanaHostname $hostName -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + $sapIns.ProvisioningState | Should -Be 'Succeeded' + } + It 'ByKeyVault' { + $hostName = 'hdb1-0' + New-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -Name $env.sapIns04 -SapMonitorName $env.sapMonitor02 -ProviderType SapHana -HanaHostname $hostName -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId $env.hanaDbPasswordSecretId -HanaDatabasePasswordKeyVaultResourceId $env.hanaDbPasswordKvResourceId -AsJob | Wait-Job + $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -Name $env.sapIns04 -SapMonitorName $env.sapMonitor02 + $sapIns.ProvisioningState | Should -Be 'Succeeded' + } + +} diff --git a/src/HanaOnAzure/test/Remove-AzSapMonitor.Recording.json b/src/HanaOnAzure/test/Remove-AzSapMonitor.Recording.json new file mode 100644 index 000000000000..9c500733e629 --- /dev/null +++ b/src/HanaOnAzure/test/Remove-AzSapMonitor.Recording.json @@ -0,0 +1,1873 @@ +{ + "Remove-AzSapMonitor+[NoContext]+Delete+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14999" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "547fdf2c-9fb6-4a0c-9e63-b82819f45563" ], + "x-ms-request-id": [ "0b8a5447-bed3-48db-9b16-6b8bd314348f" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064903Z:547fdf2c-9fb6-4a0c-9e63-b82819f45563" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:49:02 GMT" ] + }, + "ContentHeaders": { + "Expires": [ "-1" ], + "Content-Length": [ "0" ] + }, + "Content": null + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11998" ], + "x-ms-correlation-request-id": [ "2507df5e-cbdb-4022-a5ea-d83df18a9cc2" ], + "x-ms-request-id": [ "4bc43253-6d0c-4dfd-b28b-3c01e7e10138" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T064933Z:2507df5e-cbdb-4022-a5ea-d83df18a9cc2" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:49:32 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11998" ], + "x-ms-correlation-request-id": [ "4b2eb702-7bd3-49bb-9e19-555ded547a79" ], + "x-ms-request-id": [ "d620372c-98aa-4d55-8798-06450f3a7963" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065003Z:4b2eb702-7bd3-49bb-9e19-555ded547a79" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:50:03 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11997" ], + "x-ms-correlation-request-id": [ "78302fee-28e1-49d3-86f0-23733813dddd" ], + "x-ms-request-id": [ "cf358012-5fb6-4f74-bc7a-5b0d348d939c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065034Z:78302fee-28e1-49d3-86f0-23733813dddd" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:50:34 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11996" ], + "x-ms-correlation-request-id": [ "233f541e-2e75-427a-a6bb-2b9cf550a057" ], + "x-ms-request-id": [ "2f60f56f-8ca0-4936-b93e-901ceba1335c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065104Z:233f541e-2e75-427a-a6bb-2b9cf550a057" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:51:04 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+6": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11995" ], + "x-ms-correlation-request-id": [ "4c26e3e8-5eb3-4393-9874-6ac02364fc6b" ], + "x-ms-request-id": [ "987f641a-29b7-4280-b9cf-7b2994935512" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065134Z:4c26e3e8-5eb3-4393-9874-6ac02364fc6b" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:51:34 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+7": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11994" ], + "x-ms-correlation-request-id": [ "7c0eec18-5a38-4767-9592-7fdc2e05d4a5" ], + "x-ms-request-id": [ "8df18299-eb99-4d30-ac24-7adc373ed1b4" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065205Z:7c0eec18-5a38-4767-9592-7fdc2e05d4a5" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:52:05 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+8": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11993" ], + "x-ms-correlation-request-id": [ "1a487169-9044-4b26-80e6-be7dc7b62427" ], + "x-ms-request-id": [ "1dc0754a-cf4e-4367-ba75-2abd2c5b6b18" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065235Z:1a487169-9044-4b26-80e6-be7dc7b62427" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:52:35 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+9": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11992" ], + "x-ms-correlation-request-id": [ "fd65dbc5-6dcc-4012-afa7-1a816c99b826" ], + "x-ms-request-id": [ "2711d9ad-48f5-409c-aaf7-a25d4f6c4eb9" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065305Z:fd65dbc5-6dcc-4012-afa7-1a816c99b826" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:53:05 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+10": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11991" ], + "x-ms-correlation-request-id": [ "01b06d07-bb50-4868-ad24-5619aabb1daf" ], + "x-ms-request-id": [ "2fa00b3b-0a1e-40df-94d4-bb23cf9151ef" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065336Z:01b06d07-bb50-4868-ad24-5619aabb1daf" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:53:35 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+11": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11990" ], + "x-ms-correlation-request-id": [ "8b12d438-d863-4ded-8cef-c5721b9c11f3" ], + "x-ms-request-id": [ "4b30f3a9-a5aa-4a24-bbc0-f8c9570f1cb7" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065407Z:8b12d438-d863-4ded-8cef-c5721b9c11f3" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:54:06 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+12": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11989" ], + "x-ms-correlation-request-id": [ "0c8d06ab-9b36-452c-b541-c2976d471ee0" ], + "x-ms-request-id": [ "64d2e808-735b-46e8-9a25-f2f22b05c460" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065437Z:0c8d06ab-9b36-452c-b541-c2976d471ee0" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:54:36 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+13": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11988" ], + "x-ms-correlation-request-id": [ "e7618885-3011-48eb-a05b-b6a84616115f" ], + "x-ms-request-id": [ "d995b025-a482-4452-aa8e-74a4f90d5f35" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065507Z:e7618885-3011-48eb-a05b-b6a84616115f" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:55:06 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+14": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11987" ], + "x-ms-correlation-request-id": [ "f3f11122-0d04-419b-9baf-ca8f5a10ed48" ], + "x-ms-request-id": [ "ad140cd6-637d-4720-a368-c9dc1c2f3c46" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065538Z:f3f11122-0d04-419b-9baf-ca8f5a10ed48" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:55:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+15": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11986" ], + "x-ms-correlation-request-id": [ "ff0d5601-dea3-4161-a732-e891e74ef94e" ], + "x-ms-request-id": [ "0dd56e44-1b58-4bc7-8a82-d8640f140e99" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065608Z:ff0d5601-dea3-4161-a732-e891e74ef94e" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:56:08 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview+16": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11985" ], + "x-ms-correlation-request-id": [ "1c7a804d-7ae5-4c6e-8b54-0a7b8989aa1c" ], + "x-ms-request-id": [ "70451d8f-4495-40d9-a64c-c576941cf3c5" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065638Z:1c7a804d-7ae5-4c6e-8b54-0a7b8989aa1c" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:56:38 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"endTime\": \"2020-07-06T06:56:34.3622846Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2020-02-07-preview+17": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/0b8a5447-bed3-48db-9b16-6b8bd314348f?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17" ], + "x-ms-client-request-id": [ "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3", "b1b64284-9b1f-4043-9e50-ad83328725e3" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete", "Remove-AzSapMonitor_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11984" ], + "x-ms-correlation-request-id": [ "839a0a5c-204f-4d80-ae0d-1a91f779c535" ], + "x-ms-request-id": [ "c11c649c-03c9-40f9-ab17-670bec10bbbc" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065639Z:839a0a5c-204f-4d80-ae0d-1a91f779c535" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:56:38 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"0b8a5447-bed3-48db-9b16-6b8bd314348f\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T06:49:03.1389173Z\",\n \"endTime\": \"2020-07-06T06:56:34.3622846Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/sapMonitors?api-version=2020-02-07-preview+18": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/sapMonitors?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "18" ], + "x-ms-client-request-id": [ "f44e3f3b-957a-434f-8b65-f62ec4ec15f9" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065639Z:c8ddbe29-cb75-4b51-b29e-b3689febbae6" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11983" ], + "x-ms-correlation-request-id": [ "c8ddbe29-cb75-4b51-b29e-b3689febbae6" ], + "x-ms-request-id": [ "142a7d0f-6063-46b7-a5cf-c29603cdd616" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:56:38 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "5364" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"value\": [\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-j1sm2o-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-j1sm2o-test\",\n \"tags\": {\n \"key\": \"1\",\n \"key2\": \"2\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-48537d0733dfc9\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-jeiysz/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-wohtnd\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-rnwz0m-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-rnwz0m-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-9cd4a794632527\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-o3udez/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-1jx26e\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-vayh7q-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-vayh7q-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-9eec93615bc403\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-dj6nwo/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-tbmy5e\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/yemingmonitor5\",\n \"location\": \"westus2\",\n \"name\": \"yemingmonitor5\",\n \"tags\": {\n \"a\": \"b\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Deleting\",\n \"managedResourceGroupName\": \"sapmon-rg-7dc200167f3865\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.OperationalInsights/workspaces/yeminglaw\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-db-a\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/yemingmonitortest\",\n \"location\": \"westus2\",\n \"name\": \"yemingmonitortest\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-31fb7355419438\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.OperationalInsights/workspaces/yeminglaw\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }\n ]\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview", + "Content": "{\n \"location\": \"westus2\",\n \"properties\": {\n \"enableCustomerAnalytics\": true,\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt\",\n \"logAnalyticsWorkspaceId\": \"\",\n \"logAnalyticsWorkspaceSharedKey\": \"Qf/scKlrNjkyMot3WIlWvw1/p3c1+1uRtu5fRI0ihpws92OqawKurEYuODmGlkfb81gfW03zTITzOF1QARpF6w==\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "634" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1199" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "1158b127-6d8e-452a-82f5-bdf0116bbbbe" ], + "x-ms-request-id": [ "a6d30572-54fe-43a9-ad78-8f4622bd4575" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065640Z:1158b127-6d8e-452a-82f5-bdf0116bbbbe" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:56:39 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "957" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-wrlm5y-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Accepted\",\n \"managedResourceGroupName\": \"\",\n \"enableCustomerAnalytics\": true,\n \"sapMonitorCollectorVersion\": \"\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt\",\n \"logAnalyticsWorkspaceSharedKey\": \"Qf/scKlrNjkyMot3WIlWvw1/p3c1+1uRtu5fRI0ihpws92OqawKurEYuODmGlkfb81gfW03zTITzOF1QARpF6w==\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11982" ], + "x-ms-correlation-request-id": [ "59515134-21e6-40ca-8e8a-e701f1688c9e" ], + "x-ms-request-id": [ "e8b13ec4-6e70-4f89-9792-a80f83daf631" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065710Z:59515134-21e6-40ca-8e8a-e701f1688c9e" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:57:10 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11981" ], + "x-ms-correlation-request-id": [ "21a4c749-739e-4753-bfbd-9ee33371f8d5" ], + "x-ms-request-id": [ "c884343a-f7ee-4484-bd48-ae087435ee18" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065740Z:21a4c749-739e-4753-bfbd-9ee33371f8d5" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:57:40 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11980" ], + "x-ms-correlation-request-id": [ "8c19da17-8eed-4045-a4dd-e5c17e559839" ], + "x-ms-request-id": [ "4f2e3ad7-40e2-4d4b-82c2-455f48e09fee" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065811Z:8c19da17-8eed-4045-a4dd-e5c17e559839" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:58:10 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22", "23" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11979" ], + "x-ms-correlation-request-id": [ "dde9a9ea-2367-4ea0-92db-3e04195a8365" ], + "x-ms-request-id": [ "f267425f-aab1-48cb-ae3f-514c9c0d3a35" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065842Z:dde9a9ea-2367-4ea0-92db-3e04195a8365" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:58:41 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+6": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22", "23", "24" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11978" ], + "x-ms-correlation-request-id": [ "6e8d6500-181b-41a9-a2e5-1ccb195ce5f6" ], + "x-ms-request-id": [ "7c558465-c2fd-434b-99f0-a72486521541" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065912Z:6e8d6500-181b-41a9-a2e5-1ccb195ce5f6" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:59:11 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+7": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22", "23", "24", "25" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11977" ], + "x-ms-correlation-request-id": [ "36f2f490-0998-4d9b-8167-cec3c504ed1f" ], + "x-ms-request-id": [ "d7c94866-8138-4e46-9623-c200474e8893" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T065942Z:36f2f490-0998-4d9b-8167-cec3c504ed1f" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 06:59:42 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+8": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22", "23", "24", "25", "26" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11976" ], + "x-ms-correlation-request-id": [ "b26d87aa-5516-4bf4-8ef1-d50c46ab0eb5" ], + "x-ms-request-id": [ "25893f17-afd4-42dc-9416-e1ad9b2fe814" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070013Z:b26d87aa-5516-4bf4-8ef1-d50c46ab0eb5" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:00:12 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+9": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22", "23", "24", "25", "26", "27" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11975" ], + "x-ms-correlation-request-id": [ "28296e77-e6db-4ec0-81f5-86e4c879fcda" ], + "x-ms-request-id": [ "3d8fc93c-11b3-4d16-852b-c37feac93fa4" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070043Z:28296e77-e6db-4ec0-81f5-86e4c879fcda" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:00:43 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview+10": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/a6d30572-54fe-43a9-ad78-8f4622bd4575?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22", "23", "24", "25", "26", "27", "28" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11974" ], + "x-ms-correlation-request-id": [ "fd18691e-36f5-4e9a-9b49-82179ccc9420" ], + "x-ms-request-id": [ "5bf4d8cb-2b72-4896-9507-ddd193ac6ccc" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070113Z:fd18691e-36f5-4e9a-9b49-82179ccc9420" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:01:13 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"a6d30572-54fe-43a9-ad78-8f4622bd4575\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T06:56:39.8916429Z\",\n \"endTime\": \"2020-07-06T07:00:46.6877313Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview+11": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29" ], + "x-ms-client-request-id": [ "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9", "da45c2ec-7a55-491c-9dae-391becfc65e9" ], + "CommandName": [ "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor", "New-AzSapMonitor" ], + "FullCommandName": [ "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded", "New-AzSapMonitor_CreateExpanded" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070114Z:e9f7bef2-76c4-4796-bb58-539472196810" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11973" ], + "x-ms-correlation-request-id": [ "e9f7bef2-76c4-4796-bb58-539472196810" ], + "x-ms-request-id": [ "b65d6ade-5d88-476f-b196-ddad7b8e8a7c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:01:13 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "863" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-wrlm5y-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-755d7b77729881\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview+12": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-wrlm5y-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14998" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "7c1e3306-cfa1-47eb-8b8e-fd2cacb3638f" ], + "x-ms-request-id": [ "88604872-b1ca-4ed5-9c40-75b1fdb48a51" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070114Z:7c1e3306-cfa1-47eb-8b8e-fd2cacb3638f" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:01:14 GMT" ] + }, + "ContentHeaders": { + "Expires": [ "-1" ], + "Content-Length": [ "0" ] + }, + "Content": null + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2020-02-07-preview+13": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11972" ], + "x-ms-correlation-request-id": [ "7bab58aa-8ab5-4b55-b931-3d4b4774aada" ], + "x-ms-request-id": [ "d7cbdfce-7bcf-4015-94a4-2b271f00dd1a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070145Z:7bab58aa-8ab5-4b55-b931-3d4b4774aada" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:01:44 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+14": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11971" ], + "x-ms-correlation-request-id": [ "661070a6-f6a4-4091-91ef-dad15e62fb43" ], + "x-ms-request-id": [ "aef91bcf-ea7f-442f-8a77-c183c0d88e0e" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070215Z:661070a6-f6a4-4091-91ef-dad15e62fb43" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:02:14 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+15": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11970" ], + "x-ms-correlation-request-id": [ "a5df54d7-b91a-4c62-b115-2f8b1ab730d4" ], + "x-ms-request-id": [ "c7a987bd-9ab8-47b8-831d-9f4250e4264a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070245Z:a5df54d7-b91a-4c62-b115-2f8b1ab730d4" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:02:45 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+16": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11969" ], + "x-ms-correlation-request-id": [ "e0bbcdd5-def1-4d8c-8ab1-6688711d96b9" ], + "x-ms-request-id": [ "554e0a50-589d-4fd0-a44d-266121d97d3f" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070316Z:e0bbcdd5-def1-4d8c-8ab1-6688711d96b9" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:03:15 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+17": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11968" ], + "x-ms-correlation-request-id": [ "c40b6463-a656-4fbb-b6af-b320411bc834" ], + "x-ms-request-id": [ "0cd5fc6d-f342-4f54-9858-05cc4f20a260" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070346Z:c40b6463-a656-4fbb-b6af-b320411bc834" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:03:46 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+18": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11967" ], + "x-ms-correlation-request-id": [ "cfac80d1-befb-42bd-8463-32d1a41161e5" ], + "x-ms-request-id": [ "7f8ed3c4-f841-41f5-958b-f7a019e483f4" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070417Z:cfac80d1-befb-42bd-8463-32d1a41161e5" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:04:16 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+19": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11966" ], + "x-ms-correlation-request-id": [ "10d8e334-a843-47c1-9a2d-337d3444e111" ], + "x-ms-request-id": [ "dca2f72a-1984-4db7-b2ac-3b92b68ba48c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070447Z:10d8e334-a843-47c1-9a2d-337d3444e111" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:04:46 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+20": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11965" ], + "x-ms-correlation-request-id": [ "47e29108-a7bf-4cee-9eca-21d8693706d5" ], + "x-ms-request-id": [ "9cfe3d61-a53e-41a5-a44e-f818bc2f5dbf" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070518Z:47e29108-a7bf-4cee-9eca-21d8693706d5" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:05:17 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+21": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11964" ], + "x-ms-correlation-request-id": [ "40b2e2ef-cedb-473c-a953-8a939fe62ae7" ], + "x-ms-request-id": [ "bdba27d5-50e2-421c-afc8-8d566cf471b9" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070548Z:40b2e2ef-cedb-473c-a953-8a939fe62ae7" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:05:47 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+22": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11963" ], + "x-ms-correlation-request-id": [ "f61bc39f-e202-461a-9cf9-3a88530a1b35" ], + "x-ms-request-id": [ "507747bc-fd43-4361-b27c-bfa88e6c4044" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070618Z:f61bc39f-e202-461a-9cf9-3a88530a1b35" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:06:17 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+23": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11962" ], + "x-ms-correlation-request-id": [ "1232a973-3029-4f40-be28-dc557b585195" ], + "x-ms-request-id": [ "2c0f3967-f94c-420b-927d-06331e1ffe45" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070649Z:1232a973-3029-4f40-be28-dc557b585195" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:06:48 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+24": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11961" ], + "x-ms-correlation-request-id": [ "a45ba037-4d75-4aed-9dc2-a3a058a73d33" ], + "x-ms-request-id": [ "98c091cc-d41b-462a-8fd1-f0395b59227a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070719Z:a45ba037-4d75-4aed-9dc2-a3a058a73d33" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:07:18 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+25": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11960" ], + "x-ms-correlation-request-id": [ "a686ddf2-9604-4fe8-8942-466f4ef1eaeb" ], + "x-ms-request-id": [ "d4897b15-6e24-4b93-bca3-abe15e4bfbbb" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070749Z:a686ddf2-9604-4fe8-8942-466f4ef1eaeb" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:07:49 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+26": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11959" ], + "x-ms-correlation-request-id": [ "701d543a-7d89-4b9e-8430-f34be8d7f90e" ], + "x-ms-request-id": [ "a913dee9-035c-420a-b502-a00a91f431fe" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070820Z:701d543a-7d89-4b9e-8430-f34be8d7f90e" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:08:19 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview+27": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11958" ], + "x-ms-correlation-request-id": [ "d9bb0b13-4633-4f23-9e60-7e2f28e5122f" ], + "x-ms-request-id": [ "25eca236-242a-4df3-8d0c-f6be73e826fe" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070850Z:d9bb0b13-4633-4f23-9e60-7e2f28e5122f" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:08:50 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"endTime\": \"2020-07-06T07:08:45.9232238Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2020-02-07-preview+28": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/88604872-b1ca-4ed5-9c40-75b1fdb48a51?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46" ], + "x-ms-client-request-id": [ "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181", "dbb46d4d-e3e8-4f27-95ad-077235a33181" ], + "CommandName": [ "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor", "Remove-AzSapMonitor" ], + "FullCommandName": [ "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity", "Remove-AzSapMonitor_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11957" ], + "x-ms-correlation-request-id": [ "79786eb1-88f2-40fc-bb2e-e94659e2b084" ], + "x-ms-request-id": [ "1ddad028-38b2-4137-b57d-d1b2f4aba149" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070851Z:79786eb1-88f2-40fc-bb2e-e94659e2b084" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:08:50 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"88604872-b1ca-4ed5-9c40-75b1fdb48a51\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T07:01:14.6903054Z\",\n \"endTime\": \"2020-07-06T07:08:45.9232238Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitor+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/sapMonitors?api-version=2020-02-07-preview+29": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/sapMonitors?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "47" ], + "x-ms-client-request-id": [ "ffdabf2f-4ae0-4919-b5ed-cf55d0b3a42a" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070851Z:b8b2672e-5c09-4302-bdf7-b26d2bd8d306" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11956" ], + "x-ms-correlation-request-id": [ "b8b2672e-5c09-4302-bdf7-b26d2bd8d306" ], + "x-ms-request-id": [ "b6c8d7d6-14c8-42fc-8a8c-738db0d2f45f" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:08:50 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "5364" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"value\": [\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-j1sm2o-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-j1sm2o-test\",\n \"tags\": {\n \"key\": \"1\",\n \"key2\": \"2\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-48537d0733dfc9\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-jeiysz/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-wohtnd\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-rnwz0m-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-rnwz0m-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-9cd4a794632527\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-o3udez/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-1jx26e\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-vayh7q-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-vayh7q-test\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-9eec93615bc403\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-dj6nwo/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-tbmy5e\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/yemingmonitor5\",\n \"location\": \"westus2\",\n \"name\": \"yemingmonitor5\",\n \"tags\": {\n \"a\": \"b\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Deleting\",\n \"managedResourceGroupName\": \"sapmon-rg-7dc200167f3865\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.OperationalInsights/workspaces/yeminglaw\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-db-a\"\n }\n },\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/yemingmonitortest\",\n \"location\": \"westus2\",\n \"name\": \"yemingmonitortest\",\n \"tags\": {},\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-31fb7355419438\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.OperationalInsights/workspaces/yeminglaw\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }\n ]\n }" + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/Remove-AzSapMonitor.Tests.ps1 b/src/HanaOnAzure/test/Remove-AzSapMonitor.Tests.ps1 new file mode 100644 index 000000000000..e7cde48c732d --- /dev/null +++ b/src/HanaOnAzure/test/Remove-AzSapMonitor.Tests.ps1 @@ -0,0 +1,32 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzSapMonitor.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzSapMonitor' { + It 'Delete' { + Remove-AzSapMonitor -Name $env.sapMonitor02 -ResourceGroupName $env.resourceGroup + $sapMonitorList = Get-AzSapMonitor + $sapMonitorList.Name | Should -Not -Contain $env.sapMonitor02 + } + + It 'DeleteViaIdentity' { + $sapMonitor = New-AzSapMonitor -Name $env.sapMonitor02 -ResourceGroupName $env.resourceGroup -Location $env.location -EnableCustomerAnalytic ` + -MonitorSubnet $env.MonitorSubnet ` + -LogAnalyticsWorkspaceSharedKey $env.workspace02Key ` + -LogAnalyticsWorkspaceId $env.workspace02Id ` + -LogAnalyticsWorkspaceResourceId $env.workspaceResourceId02 + + Remove-AzSapMonitor -InputObject $sapMonitor + $sapMonitorList = Get-AzSapMonitor + $sapMonitorList.Name | Should -Not -Contain $env.sapMonitor02 + } +} diff --git a/src/HanaOnAzure/test/Remove-AzSapMonitorProviderInstance.Recording.json b/src/HanaOnAzure/test/Remove-AzSapMonitorProviderInstance.Recording.json new file mode 100644 index 000000000000..1c20560559aa --- /dev/null +++ b/src/HanaOnAzure/test/Remove-AzSapMonitorProviderInstance.Recording.json @@ -0,0 +1,517 @@ +{ + "Remove-AzSapMonitorProviderInstance+[NoContext]+Delete+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-p6zm1k?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1" ], + "x-ms-client-request-id": [ "69a741db-0b94-4dc5-b3d7-da38434e42cc" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_Delete" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14999" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "d00b54ff-9477-492d-95a1-d5ec30ef30bf" ], + "x-ms-request-id": [ "56a72567-8de2-48e6-83bc-721767b9a27e" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T070951Z:d00b54ff-9477-492d-95a1-d5ec30ef30bf" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:09:51 GMT" ] + }, + "ContentHeaders": { + "Expires": [ "-1" ], + "Content-Length": [ "0" ] + }, + "Content": null + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2" ], + "x-ms-client-request-id": [ "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11980" ], + "x-ms-correlation-request-id": [ "fdc9f730-6a5e-44a8-a723-85e834426359" ], + "x-ms-request-id": [ "c90519bd-b9eb-4741-9244-de7b088f4ad8" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071022Z:fdc9f730-6a5e-44a8-a723-85e834426359" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:10:22 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"56a72567-8de2-48e6-83bc-721767b9a27e\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:09:51.6310665Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2017-11-03-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3" ], + "x-ms-client-request-id": [ "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11979" ], + "x-ms-correlation-request-id": [ "9252a89e-6dd4-4c38-9af2-81838669faa4" ], + "x-ms-request-id": [ "386991b5-08d1-439b-9ece-7dc91ea7bf2c" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071052Z:9252a89e-6dd4-4c38-9af2-81838669faa4" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:10:52 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"56a72567-8de2-48e6-83bc-721767b9a27e\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:09:51.6310665Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2017-11-03-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4" ], + "x-ms-client-request-id": [ "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11978" ], + "x-ms-correlation-request-id": [ "a9b2bd4c-b930-4091-886f-c151c16fa5cc" ], + "x-ms-request-id": [ "01f190d7-c70b-4746-8bba-ef3f5606ebc5" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071122Z:a9b2bd4c-b930-4091-886f-c151c16fa5cc" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:11:22 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"56a72567-8de2-48e6-83bc-721767b9a27e\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T07:09:51.6310665Z\",\n \"endTime\": \"2020-07-06T07:10:52.4495119Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2020-02-07-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/56a72567-8de2-48e6-83bc-721767b9a27e?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "1", "2", "3", "4", "5" ], + "x-ms-client-request-id": [ "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc", "69a741db-0b94-4dc5-b3d7-da38434e42cc" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete", "Remove-AzSapMonitorProviderInstance_Delete" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11977" ], + "x-ms-correlation-request-id": [ "a378b335-4cab-4e01-9391-c239816fd3bd" ], + "x-ms-request-id": [ "9c6bf889-ffd6-4349-ae6b-46f1485f6bdf" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071123Z:a378b335-4cab-4e01-9391-c239816fd3bd" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:11:22 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"56a72567-8de2-48e6-83bc-721767b9a27e\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T07:09:51.6310665Z\",\n \"endTime\": \"2020-07-06T07:10:52.4495119Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances?api-version=2020-02-07-preview+6": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "6" ], + "x-ms-client-request-id": [ "848a312a-ea75-419c-9e19-95b7c21396fa" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071123Z:a07379e8-5e1a-4f64-8d9a-8888cfd28c4d" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11976" ], + "x-ms-correlation-request-id": [ "a07379e8-5e1a-4f64-8d9a-8888cfd28c4d" ], + "x-ms-request-id": [ "1cc4754b-44b8-4310-b200-282f4b0db74d" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:11:22 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "740" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"value\": [\n {\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-bukeg9\",\n \"location\": \"\",\n \"name\": \"sapInstance-bukeg9\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\",\\\"hanaDbPasswordKeyVaultUrl\\\":\\\"https://kv-7zeudq-test.vault.azure.net:443/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Failed\"\n }\n }\n ]\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-bukeg9?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-bukeg9?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "7" ], + "x-ms-client-request-id": [ "b50a1660-eb17-41e1-857d-9bc80fa4d324" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071123Z:44466125-e511-4cfb-b6cb-0ea9ed937428" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11975" ], + "x-ms-correlation-request-id": [ "44466125-e511-4cfb-b6cb-0ea9ed937428" ], + "x-ms-request-id": [ "e257917b-7829-4bbc-9cce-6a5610b9aa08" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:11:23 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "691" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-bukeg9\",\n \"location\": \"\",\n \"name\": \"sapInstance-bukeg9\",\n \"tags\": null,\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors/providerInstances\",\n \"properties\": {\n \"type\": \"SapHana\",\n \"properties\": \"{\\\"hanaHostname\\\":\\\"hdb1-0\\\",\\\"hanaDbName\\\":\\\"SYSTEMDB\\\",\\\"hanaDbSqlPort\\\":30015,\\\"hanaDbUsername\\\":\\\"SYSTEM\\\",\\\"hanaDbPasswordKeyVaultUrl\\\":\\\"https://kv-7zeudq-test.vault.azure.net:443/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2\\\"}\",\n \"metadata\": \"null\",\n \"provisioningState\": \"Failed\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+DeleteViaIdentity+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-bukeg9?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances/sapInstance-bukeg9?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8" ], + "x-ms-client-request-id": [ "d124e684-9e03-4030-ae80-b88859629b28" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2020-02-07-preview" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14998" ], + "azure-asyncoperation": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2020-02-07-preview" ], + "x-ms-correlation-request-id": [ "84d69392-70fc-47e9-8813-6d2cfd15fb33" ], + "x-ms-request-id": [ "3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071124Z:84d69392-70fc-47e9-8813-6d2cfd15fb33" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:11:23 GMT" ] + }, + "ContentHeaders": { + "Expires": [ "-1" ], + "Content-Length": [ "0" ] + }, + "Content": null + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2020-02-07-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8", "9" ], + "x-ms-client-request-id": [ "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11974" ], + "x-ms-correlation-request-id": [ "1ce62f25-02ac-4b16-98d8-7deca306e665" ], + "x-ms-request-id": [ "c27b0956-9d25-4132-9790-e76a00a23859" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071154Z:1ce62f25-02ac-4b16-98d8-7deca306e665" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:11:53 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:11:24.0847108Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2017-11-03-preview+4": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8", "9", "10" ], + "x-ms-client-request-id": [ "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 202, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2017-11-03-preview" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11973" ], + "x-ms-correlation-request-id": [ "dc2c5996-1ff8-4122-8b23-69a1afc9431f" ], + "x-ms-request-id": [ "fe3448d1-f690-429a-b29a-5d474d4197a6" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071224Z:dc2c5996-1ff8-4122-8b23-69a1afc9431f" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:12:24 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "176" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef\",\n \"status\": \"InProgress\",\n \"startTime\": \"2020-07-06T07:11:24.0847108Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2017-11-03-preview+5": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2017-11-03-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8", "9", "10", "11" ], + "x-ms-client-request-id": [ "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11972" ], + "x-ms-correlation-request-id": [ "9599e724-f5ab-452b-8914-a95be680b665" ], + "x-ms-request-id": [ "f73d0651-1015-4690-844d-a56f1f2194f7" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071255Z:9599e724-f5ab-452b-8914-a95be680b665" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:12:54 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T07:11:24.0847108Z\",\n \"endTime\": \"2020-07-06T07:12:24.9777386Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2020-02-07-preview+6": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.HanaOnAzure/locations/westus2/operationsStatus/3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8", "9", "10", "11", "12" ], + "x-ms-client-request-id": [ "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28", "d124e684-9e03-4030-ae80-b88859629b28" ], + "CommandName": [ "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance", "Remove-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity", "Remove-AzSapMonitorProviderInstance_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets", "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview", "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11971" ], + "x-ms-correlation-request-id": [ "cb5a7f53-d3da-4d6b-a84e-6fb1d8001ae2" ], + "x-ms-request-id": [ "45eea5e3-78ea-4b77-a790-0bbff0bf1265" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071255Z:cb5a7f53-d3da-4d6b-a84e-6fb1d8001ae2" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:12:54 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "220" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"name\": \"3e7ea1f6-e7dc-4abb-9b0e-2170fec68eef\",\n \"status\": \"Succeeded\",\n \"startTime\": \"2020-07-06T07:11:24.0847108Z\",\n \"endTime\": \"2020-07-06T07:12:24.9777386Z\",\n \"error\": {\n \"code\": \"\",\n \"message\": \"\"\n }\n }" + } + }, + "Remove-AzSapMonitorProviderInstance+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances?api-version=2020-02-07-preview+7": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test/providerInstances?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "13" ], + "x-ms-client-request-id": [ "643ee402-ffac-4c53-9f2c-7c9a36398de5" ], + "CommandName": [ "Get-AzSapMonitorProviderInstance" ], + "FullCommandName": [ "Get-AzSapMonitorProviderInstance_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11970" ], + "x-ms-correlation-request-id": [ "4a7a72ce-37d5-4a8d-b650-3664bbd08253" ], + "x-ms-request-id": [ "129cac9c-0349-4a8d-8158-fd32ab273eaf" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071255Z:4a7a72ce-37d5-4a8d-b650-3664bbd08253" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:12:55 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "18" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"value\": []\n }" + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/Remove-AzSapMonitorProviderInstance.Tests.ps1 b/src/HanaOnAzure/test/Remove-AzSapMonitorProviderInstance.Tests.ps1 new file mode 100644 index 000000000000..485f1aa6dfdc --- /dev/null +++ b/src/HanaOnAzure/test/Remove-AzSapMonitorProviderInstance.Tests.ps1 @@ -0,0 +1,27 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzSapMonitorProviderInstance.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzSapMonitorProviderInstance' { + It 'Delete' { + Remove-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -SapMonitorName $env.sapMonitor01 -Name $env.sapIns01 + $sapInsList = Get-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -SapMonitorName $env.sapMonitor01 + $sapInsList.Name | Should -Not -Contain $env.sapIns01 + } + + It 'DeleteViaIdentity' { + $sapIns = Get-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -SapMonitorName $env.sapMonitor01 -Name $env.sapIns02 + Remove-AzSapMonitorProviderInstance -InputObject $sapIns + $sapInsList = Get-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -SapMonitorName $env.sapMonitor01 + $sapInsList.Name | Should -Not -Contain $env.sapIns02 + } +} diff --git a/src/HanaOnAzure/test/Update-AzSapMonitor.Recording.json b/src/HanaOnAzure/test/Update-AzSapMonitor.Recording.json new file mode 100644 index 000000000000..794797bd5717 --- /dev/null +++ b/src/HanaOnAzure/test/Update-AzSapMonitor.Recording.json @@ -0,0 +1,112 @@ +{ + "Update-AzSapMonitor+[NoContext]+UpdateExpanded+$PATCH+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "PATCH", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview", + "Content": "{\n \"tags\": {\n \"key3\": \"3\",\n \"key2\": \"2\",\n \"key\": \"1\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "68" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071426Z:c9389691-2871-4bc0-a12f-6b6ae07e01d6" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1196" ], + "x-ms-correlation-request-id": [ "c9389691-2871-4bc0-a12f-6b6ae07e01d6" ], + "x-ms-request-id": [ "fb6f455c-3923-46f0-bfe5-68132271cafa" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:14:25 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "912" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {\n \"key\": \"1\",\n \"key2\": \"2\",\n \"key3\": \"3\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "Update-AzSapMonitor+[NoContext]+UpdateViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "2" ], + "x-ms-client-request-id": [ "a5619595-2c37-44fa-b9d8-9bb98dddb2e3" ], + "CommandName": [ "Get-AzSapMonitor" ], + "FullCommandName": [ "Get-AzSapMonitor_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071426Z:272f6055-4530-4d48-ac46-04be82923b33" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11978" ], + "x-ms-correlation-request-id": [ "272f6055-4530-4d48-ac46-04be82923b33" ], + "x-ms-request-id": [ "8b551889-fed2-4a28-9852-b7bec9aff101" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:14:25 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "912" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {\n \"key\": \"1\",\n \"key2\": \"2\",\n \"key3\": \"3\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + }, + "Update-AzSapMonitor+[NoContext]+UpdateViaIdentity+$PATCH+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview+2": { + "Request": { + "Method": "PATCH", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test?api-version=2020-02-07-preview", + "Content": "{\n \"tags\": {\n \"key\": \"1\",\n \"key2\": \"2\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "51" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200706T071437Z:7befeb37-4746-4407-a918-d486ab780cac" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1195" ], + "x-ms-correlation-request-id": [ "7befeb37-4746-4407-a918-d486ab780cac" ], + "x-ms-request-id": [ "d7f64c29-b60b-4940-951b-54511cceb9ee" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "Server": [ "nginx/1.17.8" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Mon, 06 Jul 2020 07:14:36 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "896" ], + "Content-Type": [ "application/json" ], + "Expires": [ "-1" ] + }, + "Content": "{\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.HanaOnAzure/sapMonitors/sapMonitor-4fi3jk-test\",\n \"location\": \"westus2\",\n \"name\": \"sapMonitor-4fi3jk-test\",\n \"tags\": {\n \"key\": \"1\",\n \"key2\": \"2\"\n },\n \"type\": \"Microsoft.HanaOnAzure/sapMonitors\",\n \"properties\": {\n \"provisioningState\": \"Succeeded\",\n \"managedResourceGroupName\": \"sapmon-rg-6007a622f08d10\",\n \"enableCustomerAnalytics\": false,\n \"sapMonitorCollectorVersion\": \"v2.0-beta\",\n \"logAnalyticsWorkspaceArmId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9\",\n \"monitorSubnet\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin\"\n }\n }" + } + } +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/Update-AzSapMonitor.Tests.ps1 b/src/HanaOnAzure/test/Update-AzSapMonitor.Tests.ps1 new file mode 100644 index 000000000000..740a1b650588 --- /dev/null +++ b/src/HanaOnAzure/test/Update-AzSapMonitor.Tests.ps1 @@ -0,0 +1,25 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Update-AzSapMonitor.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 'Update-AzSapMonitor' { + It 'UpdateExpanded' { + $sapMonitor = Update-AzSapMonitor -ResourceGroupName $env.resourceGroup -Name $env.sapMonitor01 -Tag @{'key'=1;'key2'=2; 'key3'=3} + $sapMonitor.Tag.Count | Should -Be 3 + } + + It 'UpdateViaIdentity' { + $sapMonitor = Get-AzSapMonitor -ResourceGroupName $env.resourceGroup -Name $env.sapMonitor01 + $sapMonitor = Update-AzSapMonitor -InputObject $sapMonitor -Tag @{'key'=1;'key2'=2} + $sapMonitor.Tag.Count | Should -Be 2 + } +} diff --git a/src/HanaOnAzure/test/env.json b/src/HanaOnAzure/test/env.json new file mode 100644 index 000000000000..62ad394290bc --- /dev/null +++ b/src/HanaOnAzure/test/env.json @@ -0,0 +1,25 @@ +{ + "hanaDbPasswordKvResourceId": "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/costmanagement-rg-r3ox95/providers/Microsoft.KeyVault/vaults/kv-7zeudq-test", + "workspace02Key": "Qf/scKlrNjkyMot3WIlWvw1/p3c1+1uRtu5fRI0ihpws92OqawKurEYuODmGlkfb81gfW03zTITzOF1QARpF6w==", + "Tenant": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "workspaceResourceId02": "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-4qo1xt", + "sapIns04": "sapInstance-kopigc", + "workspacesName01": "monitoringworkspace-dic1o9", + "workspace01Key": "Qf/scKlrNjkyMot3WIlWvw1/p3c1+1uRtu5fRI0ihpws92OqawKurEYuODmGlkfb81gfW03zTITzOF1QARpF6w==", + "sapIns03": "sapInstance-ywnfxq", + "MonitorSubnet": "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin", + "workspacesName02": "monitoringworkspace-4qo1xt", + "sapMonitor02": "sapMonitor-wrlm5y-test", + "location": "westus2", + "sapIns01": "sapInstance-p6zm1k", + "costResourceGroup": "costmanagement-rg-r3ox95", + "resourceGroup": "nancyc-hn1", + "workspaceResourceId01": "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/costmanagement-rg-r3ox95/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-dic1o9", + "workspace01Id": "09853e58-0c60-499f-bc20-beb61d92a088", + "sapMonitor01": "sapMonitor-4fi3jk-test", + "sapMonitor03": "sapMonitor-kb09s8-test", + "workspace02Id": null, + "hanaDbPasswordSecretId": "https://kv-7zeudq-test.vault.azure.net/secrets/hanaPassword/bcf58c63a98d4be4bb6e9dc1c66bcbe2", + "sapIns02": "sapInstance-bukeg9", + "SubscriptionId": "9e223dbe-3399-4e19-88eb-0975f02ac87f" +} diff --git a/src/HanaOnAzure/test/loadEnv.ps1 b/src/HanaOnAzure/test/loadEnv.ps1 new file mode 100644 index 000000000000..c4ebf2e8310c --- /dev/null +++ b/src/HanaOnAzure/test/loadEnv.ps1 @@ -0,0 +1,28 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:SubscriptionId"=$env.SubscriptionId; "*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/src/HanaOnAzure/test/readme.md b/src/HanaOnAzure/test/readme.md new file mode 100644 index 000000000000..7c752b4c8c43 --- /dev/null +++ b/src/HanaOnAzure/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/HanaOnAzure/test/utils.ps1 b/src/HanaOnAzure/test/utils.ps1 new file mode 100644 index 000000000000..4f0c71f6a508 --- /dev/null +++ b/src/HanaOnAzure/test/utils.ps1 @@ -0,0 +1,90 @@ +function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + Write-Host -ForegroundColor Yellow "Required Az.OperationalInsights and Az.KeyVault, please check if Az.OperationalInsights and Az.KeyVault installed" + + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + $env.location = 'westus2' + # For any resources you created for test, you should add it to $env here. + $env.sapMonitor01 = 'sapMonitor-' + (RandomString -allChars $false -len 6) + '-test' + $env.sapMonitor02 = 'sapMonitor-' + (RandomString -allChars $false -len 6) + '-test' + $env.sapMonitor03 = 'sapMonitor-' + (RandomString -allChars $false -len 6) + '-test' + $env.sapIns01 = 'sapInstance-' + (RandomString -allChars $false -len 6) + $env.sapIns02 = 'sapInstance-' + (RandomString -allChars $false -len 6) + $env.sapIns03 = 'sapInstance-' + (RandomString -allChars $false -len 6) + $env.sapIns04 = 'sapInstance-' + (RandomString -allChars $false -len 6) + + Write-Host -ForegroundColor Green "Create test group..." + $costResourceGroup = 'costmanagement-rg-' + (RandomString -allChars $false -len 6) + New-AzResourceGroup -Name $costResourceGroup -Location $env.location + $null = $env.Add('costResourceGroup', $costResourceGroup) + Write-Host -ForegroundColor Green 'The test group create completed.' + + Write-Host -ForegroundColor Green "Using nancyc-hn1 resource group.The resource group included HANA VM, Cann't remove." + $env.resourceGroup = 'nancyc-hn1' # The resource group deployed HANA VM, Because very difficult to deploy a HANA VM. + + Write-Host -ForegroundColor Green 'Deploying operational insights workspace' + $env.workspacesName01 = 'monitoringworkspace-' + (RandomString -allChars $false -len 6) + $env.workspacesName02 = 'monitoringworkspace-' + (RandomString -allChars $false -len 6) + # Cannot deploy template file using the New-AzDeployment, Because the all resource type cannot be exported and are not included in the template. + $workspace01 = New-AzOperationalInsightsWorkspace -ResourceGroupName $env.costResourceGroup -Name $env.workspacesName01 -Location $env.location -Sku "Standard" + $workspace02 = New-AzOperationalInsightsWorkspace -ResourceGroupName $env.costResourceGroup -Name $env.workspacesName02 -Location $env.location -Sku "Standard" + $workspace01Keys = Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName $env.costResourceGroup -Name $env.workspacesName01 + $workspace02Keys = Get-AzOperationalInsightsWorkspaceSharedKey -ResourceGroupName $env.costResourceGroup -Name $env.workspacesName01 + $null = $env.Add('workspaceResourceId01', $workspace01.ResourceId) + $null = $env.Add('workspaceResourceId02', $workspace02.ResourceId) + $null = $env.Add('workspace01Key', $workspace01Keys.PrimarySharedKey) + $null = $env.Add('workspace02Key', $workspace02Keys.PrimarySharedKey) + $null = $env.Add('workspace01Id', $workspace01.CustomerId) + $null = $env.Add('workspace02Id', $workspace02Id.CustomerId) + Write-Host -ForegroundColor Green 'The operational insights workspace deployed successfully' + + Write-Host -ForegroundColor Green 'Deploying key valut...' + $kvName = 'kv-' + (RandomString -allChars $false -len 6) + '-test' + $keyValut = New-AzKeyVault -VaultName $kvName -ResourceGroupName $env.costResourceGroup -Location $env.location + #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")] + $hanaDbPasswordSecret = Set-AzKeyVaultSecret -VaultName $kvName -Name 'hanaPassword' -SecretValue (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + $env.hanaDbPasswordKvResourceId = $keyValut.ResourceId + $env.hanaDbPasswordSecretId = $hanaDbPasswordSecret.Id + Write-Host -ForegroundColor Green 'The key valut deployed successfully' + + # Virtual network + # HANA Vm subnet + $env.MonitorSubnet = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/nancyc-hn1/providers/Microsoft.Network/virtualNetworks/vnet-sap/subnets/subnet-admin" + + # Create SAP monitor + Write-Host -ForegroundColor Green 'create SAP monitor for test...' + New-AzSapMonitor -Name $env.sapMonitor01 -ResourceGroupName $env.resourceGroup -Location $env.location -EnableCustomerAnalytic ` + -MonitorSubnet $env.MonitorSubnet ` + -LogAnalyticsWorkspaceSharedKey $env.workspace01Key ` + -LogAnalyticsWorkspaceId $env.workspace01Id ` + -LogAnalyticsWorkspaceResourceId $env.workspaceResourceId01 + Write-Host -ForegroundColor Green 'The SAP monitor created successfully' + + Write-Host -ForegroundColor Green 'create SAP instance for test...' + $hostName = 'hdb1-0' + #[SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")] + New-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -Name $env.sapIns01 -SapMonitorName $env.sapMonitor01 -ProviderType SapHana -HanaHostname $hostName -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePassword (ConvertTo-SecureString "Manager1" -AsPlainText -Force) + New-AzSapMonitorProviderInstance -ResourceGroupName $env.resourceGroup -Name $env.sapIns02 -SapMonitorName $env.sapMonitor01 -ProviderType SapHana -HanaHostname $hostName -HanaDatabaseName 'SYSTEMDB' -HanaDatabaseSqlPort 30015 -HanaDatabaseUsername SYSTEM -HanaDatabasePasswordSecretId $env.hanaDbPasswordSecretId -HanaDatabasePasswordKeyVaultResourceId $env.hanaDbPasswordKvResourceId + Write-Host -ForegroundColor Green 'The SAP instance created successfully' + + $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 + Remove-AzResourceGroup -Name $env.costResourceGroup +} + diff --git a/src/KubernetesConfiguration/Az.KubernetesConfiguration.csproj b/src/KubernetesConfiguration/Az.KubernetesConfiguration.csproj new file mode 100644 index 000000000000..e02730bca5f4 --- /dev/null +++ b/src/KubernetesConfiguration/Az.KubernetesConfiguration.csproj @@ -0,0 +1,7 @@ + + + KubernetesConfiguration + + + + \ No newline at end of file diff --git a/src/KubernetesConfiguration/Az.KubernetesConfiguration.format.ps1xml b/src/KubernetesConfiguration/Az.KubernetesConfiguration.format.ps1xml new file mode 100644 index 000000000000..969cd8bf6864 --- /dev/null +++ b/src/KubernetesConfiguration/Az.KubernetesConfiguration.format.ps1xml @@ -0,0 +1,435 @@ + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.KubernetesConfigurationIdentity + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.KubernetesConfigurationIdentity + + + + + + + + + + + + + + + + + + + + + + + + + + + ClusterName + + + ClusterResourceName + + + ClusterRp + + + ResourceGroupName + + + SourceControlConfigurationName + + + SubscriptionId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatus + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatus + + + + + + + + + + + + + + + + + + + + + ComplianceState + + + LastConfigApplied + + + Message + + + MessageLevel + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinition + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinition + + + + + + + + + + + + + + + Code + + + Message + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorProperties + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorProperties + + + + + + + + + + + + + + + ChartValue + + + ChartVersion + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ProxyResource + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ProxyResource + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.Resource + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.Resource + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperation + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperation + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationDisplay + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationDisplay + + + + + + + + + + + + + + + + + + + + + Description + + + Operation + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationList + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationList + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.Result + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.Result + + + + + + + + + + + + SampleProperty + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfiguration + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfiguration + + + + + + + + + + + + + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationList + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationList + + + + + + + + + + + + NextLink + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationProperties + + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationProperties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + EnableHelmOperator + + + OperatorInstanceName + + + OperatorNamespace + + + OperatorParam + + + OperatorScope + + + OperatorType + + + ProvisioningState + + + RepositoryPublicKey + + + RepositoryUrl + + + + + + + + \ No newline at end of file diff --git a/src/KubernetesConfiguration/Az.KubernetesConfiguration.psd1 b/src/KubernetesConfiguration/Az.KubernetesConfiguration.psd1 new file mode 100644 index 000000000000..322df04f1174 --- /dev/null +++ b/src/KubernetesConfiguration/Az.KubernetesConfiguration.psd1 @@ -0,0 +1,25 @@ +@{ + GUID = '372af220-241d-455f-a85f-8be57ce75bb7' + RootModule = './Az.KubernetesConfiguration.psm1' + ModuleVersion = '0.1.0' + CompatiblePSEditions = 'Core', 'Desktop' + Author = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' + Copyright = 'Microsoft Corporation. All rights reserved.' + Description = 'Microsoft Azure PowerShell: KubernetesConfiguration cmdlets' + PowerShellVersion = '5.1' + DotNetFrameworkVersion = '4.7.2' + RequiredAssemblies = './bin/Az.KubernetesConfiguration.private.dll' + RequiredModules = @(@{ModuleName = 'Az.Accounts'; ModuleVersion = '1.9.0'; }) + FormatsToProcess = './Az.KubernetesConfiguration.format.ps1xml' + FunctionsToExport = 'Get-AzKubernetesConfiguration', 'New-AzKubernetesConfiguration', 'Remove-AzKubernetesConfiguration' + AliasesToExport = '*' + PrivateData = @{ + PSData = @{ + Tags = 'Azure', 'ResourceManager', 'ARM', 'PSModule', 'KubernetesConfiguration' + LicenseUri = 'https://aka.ms/azps-license' + ProjectUri = 'https://github.com/Azure/azure-powershell' + ReleaseNotes = '* the first preview release' + } + } +} diff --git a/src/KubernetesConfiguration/Az.KubernetesConfiguration.psm1 b/src/KubernetesConfiguration/Az.KubernetesConfiguration.psm1 new file mode 100644 index 000000000000..f3bcf52e29eb --- /dev/null +++ b/src/KubernetesConfiguration/Az.KubernetesConfiguration.psm1 @@ -0,0 +1,109 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # + # Copyright Microsoft Corporation + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # http://www.apache.org/licenses/LICENSE-2.0 + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'1.7.4' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 1.7.4 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 1.7.4 or greater. For installation instructions, please see: https://docs.microsoft.com/en-us/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'1.7.4') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 1.7.4 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to remove '.PSSharedModules' in your home directory. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.KubernetesConfiguration.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.KubernetesConfiguration.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/KubernetesConfiguration/ChangeLog.md b/src/KubernetesConfiguration/ChangeLog.md new file mode 100644 index 000000000000..b76ecb79cf4a --- /dev/null +++ b/src/KubernetesConfiguration/ChangeLog.md @@ -0,0 +1,24 @@ + +## Upcoming Release + +## Version 0.1.0 +* the first preview release + diff --git a/src/KubernetesConfiguration/KubernetesConfiguration.sln b/src/KubernetesConfiguration/KubernetesConfiguration.sln new file mode 100644 index 000000000000..db04f5751245 --- /dev/null +++ b/src/KubernetesConfiguration/KubernetesConfiguration.sln @@ -0,0 +1,48 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Accounts", "..\Accounts\Accounts\Accounts.csproj", "{142D7B0B-388A-4CEB-A228-7F6D423C5C2E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication", "..\Accounts\Authentication\Authentication.csproj", "{62843FE6-7575-4D88-B989-7DF7EEC0BC01}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication.ResourceManager", "..\Accounts\Authentication.ResourceManager\Authentication.ResourceManager.csproj", "{442C609B-A431-4A71-B289-08F0B63C83E5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authenticators", "..\Accounts\Authenticators\Authenticators.csproj", "{59E8F6B8-8F0E-403F-B88B-9736DBC396D9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Az.KubernetesConfiguration", "Az.KubernetesConfiguration.csproj", "{1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.Build.0 = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.Build.0 = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.Build.0 = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.Build.0 = Release|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1C203C0C-E0FD-40D2-B79E-C6DA52E4E350}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F9B3D96E-9680-40BE-A917-02EE655D6030} + EndGlobalSection +EndGlobal diff --git a/src/KubernetesConfiguration/MSSharedLibKey.snk b/src/KubernetesConfiguration/MSSharedLibKey.snk new file mode 100644 index 000000000000..695f1b38774e Binary files /dev/null and b/src/KubernetesConfiguration/MSSharedLibKey.snk differ diff --git a/src/KubernetesConfiguration/Properties/AssemblyInfo.cs b/src/KubernetesConfiguration/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..508567385a36 --- /dev/null +++ b/src/KubernetesConfiguration/Properties/AssemblyInfo.cs @@ -0,0 +1,28 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Microsoft Azure Powershell - KubernetesConfiguration")] +[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] +[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] +[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] + +[assembly: ComVisible(false)] +[assembly: CLSCompliant(false)] +[assembly: Guid("D22E4B20-44C5-4DD8-A76B-35423C573AE0")] +[assembly: AssemblyVersion("0.1.0")] +[assembly: AssemblyFileVersion("0.1.0")] \ No newline at end of file diff --git a/src/KubernetesConfiguration/build-module.ps1 b/src/KubernetesConfiguration/build-module.ps1 new file mode 100644 index 000000000000..cb0ecba241a2 --- /dev/null +++ b/src/KubernetesConfiguration/build-module.ps1 @@ -0,0 +1,153 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $Isolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.KubernetesConfiguration' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: KubernetesConfiguration cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.KubernetesConfiguration.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/src/KubernetesConfiguration/check-dependencies.ps1 b/src/KubernetesConfiguration/check-dependencies.ps1 new file mode 100644 index 000000000000..5cd7ab5c808f --- /dev/null +++ b/src/KubernetesConfiguration/check-dependencies.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '1.7.4' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -versionMinimum '' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and (-not (Test-Path -Path $resourceModule))) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest-beta .\readme.md --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/src/KubernetesConfiguration/custom/Az.KubernetesConfiguration.custom.psm1 b/src/KubernetesConfiguration/custom/Az.KubernetesConfiguration.custom.psm1 new file mode 100644 index 000000000000..b34da4ee045e --- /dev/null +++ b/src/KubernetesConfiguration/custom/Az.KubernetesConfiguration.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.KubernetesConfiguration.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.KubernetesConfiguration.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/KubernetesConfiguration/custom/New-AzKubernetesConfiguration.ps1 b/src/KubernetesConfiguration/custom/New-AzKubernetesConfiguration.ps1 new file mode 100644 index 000000000000..0bdddbedd4ff --- /dev/null +++ b/src/KubernetesConfiguration/custom/New-AzKubernetesConfiguration.ps1 @@ -0,0 +1,203 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create a new Kubernetes Source Control Configuration. +.Description +Create a new Kubernetes Source Control Configuration. +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/new-azsourcecontrolconfiguration +#> +function New-AzKubernetesConfiguration { + [OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration])] + [CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] + param( + [Parameter(Mandatory, HelpMessage="The name of the kubernetes cluster.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(HelpMessage="The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(Mandatory, HelpMessage="Name of the Source Control Configuration.")] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(Mandatory, HelpMessage="The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(HelpMessage="The Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(Mandatory, HelpMessage="Url of the SourceControl Repository.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Url of the SourceControl Repository. + ${RepositoryUrl}, + + [Parameter(HelpMessage="Option to enable Helm Operator for this git configuration.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [switch] + # Option to enable Helm Operator for this git configuration. + ${EnableHelmOperator}, + + [Parameter(HelpMessage="Values override for the operator Helm chart.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Values override for the operator Helm chart. + ${HelmOperatorChartValues}, + + [Parameter(HelpMessage="Version of the operator Helm chart.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Version of the operator Helm chart. + ${HelmOperatorChartVersion}, + + [Parameter(HelpMessage="Instance name of the operator - identifying the specific configuration.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Instance name of the operator - identifying the specific configuration. + ${OperatorInstanceName}, + + [Parameter(HelpMessage="The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # The namespace to which this operator is installed to. + # Maximum of 253 lower case alphanumeric characters, hyphen and period only. + ${OperatorNamespace}, + + [Parameter(HelpMessage="Any Parameters for the Operator instance in string format.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Any Parameters for the Operator instance in string format. + ${OperatorParameters}, + + [Parameter(HelpMessage="If passed set the scope of the Configuration to Cluster (default is nameSpace).")] + [switch] + ${ClusterScoped}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} + ) + + process { + + if ($PSBoundParameters.ContainsKey('EnableHelmOperator')) { + $PSBoundParameters.EnableHelmOperator = [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator]::True + } else { + $PSBoundParameters.EnableHelmOperator = [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator]::False + } + + if ($PSBoundParameters.ContainsKey('ClusterScoped')) { + $PSBoundParameters.OperatorScope = [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope]::Cluster + } else { + $PSBoundParameters.OperatorScope = [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope]::Namespace + } + + if ($PSBoundParameters.ContainsKey('ClusterType')) { + if ($ClusterType -eq 'ManagedClusters') { + $PSBoundParameters.Add('ClusterRp', 'Microsoft.ContainerService') + } elseif ($ClusterType -eq 'ConnectedClusters') { + $PSBoundParameters.Add('ClusterRp', 'Microsoft.Kubernetes') + } + } else { + $PSBoundParameters.Add('ClusterType', 'ConnectedClusters') + $PSBoundParameters.Add('ClusterRp', 'Microsoft.Kubernetes') + } + + if ($PSBoundParameters.ContainsKey('HelmOperatorChartValues')) { + $PSBoundParameters.Add('HelmOperatorPropertyChartValue', $HelmOperatorChartValues) + $null = $PSBoundParameters.Remove('HelmOperatorChartValues') + } + + if ($PSBoundParameters.ContainsKey('HelmOperatorChartVersion')) { + $PSBoundParameters.Add('HelmOperatorPropertyChartVersion', $HelmOperatorChartVersion) + $null = $PSBoundParameters.Remove('HelmOperatorChartVersion') + } + + if ($PSBoundParameters.ContainsKey('OperatorParam')) { + $PSBoundParameters.Add('OperatorParameters', $OperatorParam) + $null = $PSBoundParameters.Remove('OperatorParam') + } + $PSBoundParameters.Add('OperatorType', [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType]::Flux) + + + Az.KubernetesConfiguration.internal\New-AzKubernetesConfiguration @PSBoundParameters + } +} diff --git a/src/KubernetesConfiguration/custom/Remove-AzKubernetesConfiguration.ps1 b/src/KubernetesConfiguration/custom/Remove-AzKubernetesConfiguration.ps1 new file mode 100644 index 000000000000..ad8e47cb8efa --- /dev/null +++ b/src/KubernetesConfiguration/custom/Remove-AzKubernetesConfiguration.ps1 @@ -0,0 +1,165 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Description +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the kubernetes cluster. + [ClusterResourceName ]: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + [ClusterRp ]: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [SourceControlConfigurationName ]: Name of the Source Control Configuration. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/remove-azkubernetesconfiguration +#> +function Remove-AzKubernetesConfiguration { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory, HelpMessage="The name of the kubernetes cluster.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory, HelpMessage="The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(ParameterSetName='Delete', Mandatory, HelpMessage="Name of the Source Control Configuration.")] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory, HelpMessage="The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete', HelpMessage="The Azure subscription ID.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline, HelpMessage="Identity Parameter")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + + + process { + + if ($PSBoundParameters.ContainsKey('ClusterType')) { + if ($ClusterType -eq 'ManagedClusters') { + $PSBoundParameters.Add('ClusterRp', 'Microsoft.ContainerService') + } elseif ($ClusterType -eq 'ConnectedClusters') { + $PSBoundParameters.Add('ClusterRp', 'Microsoft.Kubernetes') + } + } + + Az.KubernetesConfiguration.internal\Remove-AzKubernetesConfiguration @PSBoundParameters + } +} diff --git a/src/KubernetesConfiguration/custom/readme.md b/src/KubernetesConfiguration/custom/readme.md new file mode 100644 index 000000000000..64570781f985 --- /dev/null +++ b/src/KubernetesConfiguration/custom/readme.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.KubernetesConfiguration` 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.KubernetesConfiguration.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.KubernetesConfiguration` 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.KubernetesConfiguration.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.KubernetesConfiguration.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundemental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.KubernetesConfiguration`. 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.KubernetesConfiguration.Models.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propegated to reference documentation via [help comments](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.KubernetesConfiguration`. +- `Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.KubernetesConfiguration`. For more information, see [readme.md](..\internal/readme.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.ProfileAttribute` + - Used in C# and script cmdlets to define which Azure profiles the cmdlet supports. This is only supported for Azure (`--azure`) modules. \ No newline at end of file diff --git a/src/KubernetesConfiguration/examples/Get-AzKubernetesConfiguration.md b/src/KubernetesConfiguration/examples/Get-AzKubernetesConfiguration.md new file mode 100644 index 000000000000..a79c8c839763 --- /dev/null +++ b/src/KubernetesConfiguration/examples/Get-AzKubernetesConfiguration.md @@ -0,0 +1,46 @@ +### Example 1: Get all configurations of kubernetes cluster +```powershell +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets all configurations of kubernetes cluster. + +### Example 2: Get a configuration of kubernetes cluster by name +```powershell +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters -Name conf-t02 + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets a configuration of kubernetes cluster by name. + +### Example 3: Get a configuration of kubernetes cluster by object +```powershell +PS C:\> $kubConf = New-AzKubernetesConfiguration -Name conf-test02 -ClusterName connaks-dkc29c -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx +PS C:\> Get-AzKubernetesConfiguration -InputObject $kubConf + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets a configuration of kubernetes cluster by object. + +### Example 4: Get a configuration of kubernetes cluster by pipeline +```powershell +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/connectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/conf-test01'} | Get-AzKubernetesConfiguration + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets a configuration of kubernetes cluster by pipeline. + + diff --git a/src/KubernetesConfiguration/examples/New-AzKubernetesConfiguration.md b/src/KubernetesConfiguration/examples/New-AzKubernetesConfiguration.md new file mode 100644 index 000000000000..4372ff73606b --- /dev/null +++ b/src/KubernetesConfiguration/examples/New-AzKubernetesConfiguration.md @@ -0,0 +1,11 @@ +### Example 1: Create a configuation for kubernetes cluster +```powershell +PS C:\> New-AzKubernetesConfiguration -Name conf-test01 -ClusterName connaks-d983yc -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command creates a configuation for kubernetes cluster. + diff --git a/src/KubernetesConfiguration/examples/Remove-AzKubernetesConfiguration.md b/src/KubernetesConfiguration/examples/Remove-AzKubernetesConfiguration.md new file mode 100644 index 000000000000..7af70f7904d8 --- /dev/null +++ b/src/KubernetesConfiguration/examples/Remove-AzKubernetesConfiguration.md @@ -0,0 +1,17 @@ +### Example 1: Remove a configuation of kubernetes cluster by name +```powershell +PS C:\> Remove-AzKubernetesConfiguration -ClusterName connaks-d983yc -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test01 + +``` + +This command removes a configuation of kubernetes cluster by name. + +### Example 2: Remove a configuation of kubernetes cluster by object +```powershell +PS C:\> $kubConf = Get-AzKubernetesConfiguration -ClusterName connaks-dkc29c -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test02 -ClusterRp Microsoft.Kubernetes +PS C:\> Remove-AzKubernetesConfiguration -InputObject $kubConf + +``` + +This command removes a configuation of kubernetes cluster by object. + diff --git a/src/KubernetesConfiguration/export-surface.ps1 b/src/KubernetesConfiguration/export-surface.ps1 new file mode 100644 index 000000000000..577c9c6407c9 --- /dev/null +++ b/src/KubernetesConfiguration/export-surface.ps1 @@ -0,0 +1,40 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.KubernetesConfiguration.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.KubernetesConfiguration' +$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/KubernetesConfiguration/exports/Get-AzKubernetesConfiguration.ps1 b/src/KubernetesConfiguration/exports/Get-AzKubernetesConfiguration.ps1 new file mode 100644 index 000000000000..482d169071f9 --- /dev/null +++ b/src/KubernetesConfiguration/exports/Get-AzKubernetesConfiguration.ps1 @@ -0,0 +1,210 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets details of the Source Control Configuration. +.Description +Gets details of the Source Control Configuration. +.Example +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +.Example +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters -Name conf-t02 + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +.Example +PS C:\> $kubConf = New-AzKubernetesConfiguration -Name conf-test02 -ClusterName connaks-dkc29c -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx +PS C:\> Get-AzKubernetesConfiguration -InputObject $kubConf + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +.Example +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/connectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/conf-test01'} | Get-AzKubernetesConfiguration + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the kubernetes cluster. + [ClusterResourceName ]: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + [ClusterRp ]: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [SourceControlConfigurationName ]: Name of the Source Control Configuration. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/get-azkubernetesconfiguration +#> +function Get-AzKubernetesConfiguration { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + ${ClusterRp}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.KubernetesConfiguration.private\Get-AzKubernetesConfiguration_Get'; + GetViaIdentity = 'Az.KubernetesConfiguration.private\Get-AzKubernetesConfiguration_GetViaIdentity'; + List = 'Az.KubernetesConfiguration.private\Get-AzKubernetesConfiguration_List'; + } + if (('Get', 'List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/KubernetesConfiguration/exports/New-AzKubernetesConfiguration.ps1 b/src/KubernetesConfiguration/exports/New-AzKubernetesConfiguration.ps1 new file mode 100644 index 000000000000..763d121c12a2 --- /dev/null +++ b/src/KubernetesConfiguration/exports/New-AzKubernetesConfiguration.ps1 @@ -0,0 +1,203 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create a new Kubernetes Source Control Configuration. +.Description +Create a new Kubernetes Source Control Configuration. +.Example +PS C:\> New-AzKubernetesConfiguration -Name conf-test01 -ClusterName connaks-d983yc -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/new-azsourcecontrolconfiguration +#> +function New-AzKubernetesConfiguration { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Url of the SourceControl Repository. + ${RepositoryUrl}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.Management.Automation.SwitchParameter] + # Option to enable Helm Operator for this git configuration. + ${EnableHelmOperator}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Values override for the operator Helm chart. + ${HelmOperatorChartValues}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Version of the operator Helm chart. + ${HelmOperatorChartVersion}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Instance name of the operator - identifying the specific configuration. + ${OperatorInstanceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # The namespace to which this operator is installed to. + # Maximum of 253 lower case alphanumeric characters, hyphen and period only. + ${OperatorNamespace}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Any Parameters for the Operator instance in string format. + ${OperatorParameters}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.Management.Automation.SwitchParameter] + # If passed set the scope of the Configuration to Cluster (default is nameSpace). + ${ClusterScoped}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.KubernetesConfiguration.custom\New-AzKubernetesConfiguration'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/KubernetesConfiguration/exports/ProxyCmdletDefinitions.ps1 b/src/KubernetesConfiguration/exports/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..514252a67bc0 --- /dev/null +++ b/src/KubernetesConfiguration/exports/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,609 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Gets details of the Source Control Configuration. +.Description +Gets details of the Source Control Configuration. +.Example +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +.Example +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters -Name conf-t02 + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +.Example +PS C:\> $kubConf = New-AzKubernetesConfiguration -Name conf-test02 -ClusterName connaks-dkc29c -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx +PS C:\> Get-AzKubernetesConfiguration -InputObject $kubConf + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +.Example +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/connectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/conf-test01'} | Get-AzKubernetesConfiguration + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the kubernetes cluster. + [ClusterResourceName ]: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + [ClusterRp ]: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [SourceControlConfigurationName ]: Name of the Source Control Configuration. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/get-azkubernetesconfiguration +#> +function Get-AzKubernetesConfiguration { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + ${ClusterRp}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.KubernetesConfiguration.private\Get-AzKubernetesConfiguration_Get'; + GetViaIdentity = 'Az.KubernetesConfiguration.private\Get-AzKubernetesConfiguration_GetViaIdentity'; + List = 'Az.KubernetesConfiguration.private\Get-AzKubernetesConfiguration_List'; + } + if (('Get', 'List') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create a new Kubernetes Source Control Configuration. +.Description +Create a new Kubernetes Source Control Configuration. +.Example +PS C:\> New-AzKubernetesConfiguration -Name conf-test01 -ClusterName connaks-d983yc -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/new-azsourcecontrolconfiguration +#> +function New-AzKubernetesConfiguration { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Url of the SourceControl Repository. + ${RepositoryUrl}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.Management.Automation.SwitchParameter] + # Option to enable Helm Operator for this git configuration. + ${EnableHelmOperator}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Values override for the operator Helm chart. + ${HelmOperatorChartValues}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Version of the operator Helm chart. + ${HelmOperatorChartVersion}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Instance name of the operator - identifying the specific configuration. + ${OperatorInstanceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # The namespace to which this operator is installed to. + # Maximum of 253 lower case alphanumeric characters, hyphen and period only. + ${OperatorNamespace}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Any Parameters for the Operator instance in string format. + ${OperatorParameters}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.Management.Automation.SwitchParameter] + # If passed set the scope of the Configuration to Cluster (default is nameSpace). + ${ClusterScoped}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.KubernetesConfiguration.custom\New-AzKubernetesConfiguration'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Description +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Example +PS C:\> Remove-AzKubernetesConfiguration -ClusterName connaks-d983yc -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test01 + +.Example +PS C:\> $kubConf = Get-AzKubernetesConfiguration -ClusterName connaks-dkc29c -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test02 -ClusterRp Microsoft.Kubernetes +PS C:\> Remove-AzKubernetesConfiguration -InputObject $kubConf + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the kubernetes cluster. + [ClusterResourceName ]: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + [ClusterRp ]: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [SourceControlConfigurationName ]: Name of the Source Control Configuration. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/remove-azkubernetesconfiguration +#> +function Remove-AzKubernetesConfiguration { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.KubernetesConfiguration.custom\Remove-AzKubernetesConfiguration'; + DeleteViaIdentity = 'Az.KubernetesConfiguration.custom\Remove-AzKubernetesConfiguration'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/KubernetesConfiguration/exports/Remove-AzKubernetesConfiguration.ps1 b/src/KubernetesConfiguration/exports/Remove-AzKubernetesConfiguration.ps1 new file mode 100644 index 000000000000..ffe07602cecd --- /dev/null +++ b/src/KubernetesConfiguration/exports/Remove-AzKubernetesConfiguration.ps1 @@ -0,0 +1,196 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Description +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Example +PS C:\> Remove-AzKubernetesConfiguration -ClusterName connaks-d983yc -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test01 + +.Example +PS C:\> $kubConf = Get-AzKubernetesConfiguration -ClusterName connaks-dkc29c -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test02 -ClusterRp Microsoft.Kubernetes +PS C:\> Remove-AzKubernetesConfiguration -InputObject $kubConf + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the kubernetes cluster. + [ClusterResourceName ]: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + [ClusterRp ]: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [SourceControlConfigurationName ]: Name of the Source Control Configuration. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/remove-azkubernetesconfiguration +#> +function Remove-AzKubernetesConfiguration { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.KubernetesConfiguration.custom\Remove-AzKubernetesConfiguration'; + DeleteViaIdentity = 'Az.KubernetesConfiguration.custom\Remove-AzKubernetesConfiguration'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/KubernetesConfiguration/exports/readme.md b/src/KubernetesConfiguration/exports/readme.md new file mode 100644 index 000000000000..3a0fc63a133c --- /dev/null +++ b/src/KubernetesConfiguration/exports/readme.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.KubernetesConfiguration`. No other cmdlets in this repository are directly exported. What that means is the `Az.KubernetesConfiguration` module will run [Export-ModuleMember](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.KubernetesConfiguration.private.dll`) and from the `..\custom\Az.KubernetesConfiguration.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.KubernetesConfiguration.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/KubernetesConfiguration/generate-help.ps1 b/src/KubernetesConfiguration/generate-help.ps1 new file mode 100644 index 000000000000..d5297231c015 --- /dev/null +++ b/src/KubernetesConfiguration/generate-help.ps1 @@ -0,0 +1,73 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.KubernetesConfiguration.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.KubernetesConfiguration.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/KubernetesConfiguration/generate-info.json b/src/KubernetesConfiguration/generate-info.json new file mode 100644 index 000000000000..2550f04b74e6 --- /dev/null +++ b/src/KubernetesConfiguration/generate-info.json @@ -0,0 +1,8 @@ +{ + "swagger_commit": "734319d8284f0bb20ba521808630be3e235ea344", + "autorest_core": "3.0.6282", + "autorest": "3.0.6187", + "node": "v10.16.0", + "autorest_remodeler": "2.1.27", + "autorest_powershell": "2.1.394" +} diff --git a/src/KubernetesConfiguration/generated/Module.cs b/src/KubernetesConfiguration/generated/Module.cs new file mode 100644 index 000000000000..fb1a4bd3ecae --- /dev/null +++ b/src/KubernetesConfiguration/generated/Module.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpPipeline _pipelineWithProxy; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// Backing field for property. + private static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module _instance; + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module Instance => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module._instance?? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module._instance = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module()); + + /// The Name of this module + public string Name => @"Az.KubernetesConfiguration"; + + /// 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.KubernetesConfiguration"; + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_handler.UseProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + } + + /// Creates the module instance. + private Module() + { + /// constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + _webProxy.UseDefaultCredentials = proxyUseDefaultCredentials; + _handler.UseProxy = proxy != null; + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/KubernetesConfiguration.cs b/src/KubernetesConfiguration/generated/api/KubernetesConfiguration.cs new file mode 100644 index 000000000000..669101ad32a8 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/KubernetesConfiguration.cs @@ -0,0 +1,1053 @@ +// 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.KubernetesConfiguration +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// + /// Low-level API implementation for the KubernetesConfiguration service. + /// + public partial class KubernetesConfiguration + { + + /// + /// List all the available operations the KubernetesConfiguration resource provider supports. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.KubernetesConfiguration/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,eventListener,sender); + } + } + + /// + /// List all the available operations the KubernetesConfiguration resource provider supports. + /// + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.KubernetesConfiguration/operations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.KubernetesConfiguration/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.KubernetesConfiguration/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// Create a new Kubernetes Source Control Configuration. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// Name of the Source Control Configuration. + /// Properties necessary to Create KubernetesConfiguration. + /// 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.KubernetesConfiguration.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 SourceControlConfigurationsCreateOrUpdate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration 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.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/" + + global::System.Uri.EscapeDataString(clusterRp) + + "/" + + global::System.Uri.EscapeDataString(clusterResourceName) + + "/" + + global::System.Uri.EscapeDataString(clusterName) + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + + global::System.Uri.EscapeDataString(sourceControlConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsCreateOrUpdate_Call(request,onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// Create a new Kubernetes Source Control Configuration. + /// + /// Properties necessary to Create KubernetesConfiguration. + /// 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.KubernetesConfiguration.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 SourceControlConfigurationsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration 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.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterRp = _match.Groups["clusterRp"].Value; + var clusterResourceName = _match.Groups["clusterResourceName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + var sourceControlConfigurationName = _match.Groups["sourceControlConfigurationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + clusterRp + + "/" + + clusterResourceName + + "/" + + clusterName + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + + sourceControlConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsCreateOrUpdate_Call(request,onOk,onCreated,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 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.KubernetesConfiguration.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 SourceControlConfigurationsCreateOrUpdate_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.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// Name of the Source Control Configuration. + /// Properties necessary to Create KubernetesConfiguration. + /// 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 SourceControlConfigurationsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration body, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); + await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); + await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); + await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + await eventListener.AssertNotNull(nameof(sourceControlConfigurationName),sourceControlConfigurationName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// + /// This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source + /// repo. + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// Name of the Source Control Configuration. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 SourceControlConfigurationsDelete(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/" + + global::System.Uri.EscapeDataString(clusterRp) + + "/" + + global::System.Uri.EscapeDataString(clusterResourceName) + + "/" + + global::System.Uri.EscapeDataString(clusterName) + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + + global::System.Uri.EscapeDataString(sourceControlConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// + /// This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source + /// repo. + /// + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 SourceControlConfigurationsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterRp = _match.Groups["clusterRp"].Value; + var clusterResourceName = _match.Groups["clusterResourceName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + var sourceControlConfigurationName = _match.Groups["sourceControlConfigurationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + clusterRp + + "/" + + clusterResourceName + + "/" + + clusterName + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + + sourceControlConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns 204 (NoContent). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 SourceControlConfigurationsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + // this operation supports x-ms-long-running-operation + var _originalUri = request.RequestUri.AbsoluteUri; + // declared final-state-via: default + var _finalUri = _response.GetFirstHeader(@"Location"); + var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = _response.GetFirstHeader(@"Location"); + while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + + // get the delay before polling. (default to 30 seconds if not present) + int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // start the delay timer (we'll await later...) + var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); + + // while we wait, let's grab the headers and get ready to poll. + if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { + asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { + location = _response.GetFirstHeader(@"Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get); + + // and let's look at the current response body and see if we have some information we can give back to the listener + var content = await _response.Content.ReadAsStringAsync(); + await waiting; + + // check for cancellation + if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + try { + if( Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + var state = json.Property("properties")?.PropertyT("provisioningState") ?? json.PropertyT("status"); + if( state is null ) + { + // the body doesn't contain any information that has the state of the LRO + // we're going to just get out, and let the consumer have the result + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + switch( state?.ToString()?.ToLower() ) + { + case "succeeded": + case "failed": + case "canceled": + // we're done polling. + break; + + default: + // need to keep polling! + _response.StatusCode = global::System.Net.HttpStatusCode.Created; + continue; + } + } + } catch { + // if we run into a problem peeking into the result, + // we really don't want to do anything special. + } + } + + // check for terminal status code + if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + continue; + } + // we are done polling, do a request on final target? + if (!string.IsNullOrWhiteSpace(_finalUri)) + { + // create a new request with the final uri + request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + break; + } + } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// Name of the Source Control Configuration. + /// 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 SourceControlConfigurationsDelete_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); + await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); + await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); + await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + await eventListener.AssertNotNull(nameof(sourceControlConfigurationName),sourceControlConfigurationName); + } + } + + /// Gets details of the Source Control Configuration. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// Name of the Source Control Configuration. + /// 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.KubernetesConfiguration.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 SourceControlConfigurationsGet(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/" + + global::System.Uri.EscapeDataString(clusterRp) + + "/" + + global::System.Uri.EscapeDataString(clusterResourceName) + + "/" + + global::System.Uri.EscapeDataString(clusterName) + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + + global::System.Uri.EscapeDataString(sourceControlConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Gets details of the Source Control Configuration. + /// + /// 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.KubernetesConfiguration.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 SourceControlConfigurationsGetViaIdentity(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.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterRp = _match.Groups["clusterRp"].Value; + var clusterResourceName = _match.Groups["clusterResourceName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + var sourceControlConfigurationName = _match.Groups["sourceControlConfigurationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + clusterRp + + "/" + + clusterResourceName + + "/" + + clusterName + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + + sourceControlConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 SourceControlConfigurationsGet_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.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// Name of the Source Control Configuration. + /// 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 SourceControlConfigurationsGet_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); + await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); + await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); + await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + await eventListener.AssertNotNull(nameof(sourceControlConfigurationName),sourceControlConfigurationName); + } + } + + /// List all Source Control Configurations. + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// 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.KubernetesConfiguration.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 SourceControlConfigurationsList(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/" + + global::System.Uri.EscapeDataString(clusterRp) + + "/" + + global::System.Uri.EscapeDataString(clusterResourceName) + + "/" + + global::System.Uri.EscapeDataString(clusterName) + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// List all Source Control Configurations. + /// + /// 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.KubernetesConfiguration.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 SourceControlConfigurationsListViaIdentity(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.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + var apiVersion = @"2019-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var clusterRp = _match.Groups["clusterRp"].Value; + var clusterResourceName = _match.Groups["clusterResourceName"].Value; + var clusterName = _match.Groups["clusterName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/" + + clusterRp + + "/" + + clusterResourceName + + "/" + + clusterName + + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SourceControlConfigurationsList_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 SourceControlConfigurationsList_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.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// The name of the resource group. + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes + /// (for OnPrem K8S clusters). + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or + /// connectedClusters (for OnPrem K8S clusters). + /// The name of the kubernetes cluster. + /// 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 SourceControlConfigurationsList_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); + await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); + await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); + await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); + await eventListener.AssertNotNull(nameof(clusterName),clusterName); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.PowerShell.cs new file mode 100644 index 000000000000..af82cdcd764f --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Compliance Status details + [System.ComponentModel.TypeConverter(typeof(ComplianceStatusTypeConverter))] + public partial class ComplianceStatus + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ComplianceStatus(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).ComplianceState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState?) content.GetValueForProperty("ComplianceState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).ComplianceState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).LastConfigApplied = (global::System.DateTime?) content.GetValueForProperty("LastConfigApplied",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).LastConfigApplied, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).MessageLevel = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel?) content.GetValueForProperty("MessageLevel",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).MessageLevel, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel.CreateFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ComplianceStatus(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).ComplianceState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState?) content.GetValueForProperty("ComplianceState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).ComplianceState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).LastConfigApplied = (global::System.DateTime?) content.GetValueForProperty("LastConfigApplied",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).LastConfigApplied, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).MessageLevel = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel?) content.GetValueForProperty("MessageLevel",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)this).MessageLevel, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel.CreateFrom); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ComplianceStatus(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.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ComplianceStatus(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.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Compliance Status details + [System.ComponentModel.TypeConverter(typeof(ComplianceStatusTypeConverter))] + public partial interface IComplianceStatus + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.TypeConverter.cs new file mode 100644 index 000000000000..ff38e4966b86 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ComplianceStatusTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ComplianceStatus.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ComplianceStatus.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ComplianceStatus.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.cs new file mode 100644 index 000000000000..5a038ecdf56f --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.cs @@ -0,0 +1,100 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Compliance Status details + public partial class ComplianceStatus : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? _complianceState; + + /// The compliance state of the configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceState { get => this._complianceState; } + + /// Backing field for property. + private global::System.DateTime? _lastConfigApplied; + + /// Datetime the configuration was last applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public global::System.DateTime? LastConfigApplied { get => this._lastConfigApplied; set => this._lastConfigApplied = value; } + + /// Backing field for property. + private string _message; + + /// Message from when the configuration was applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Message { get => this._message; set => this._message = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? _messageLevel; + + /// Level of the message. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? MessageLevel { get => this._messageLevel; set => this._messageLevel = value; } + + /// Internal Acessors for ComplianceState + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal.ComplianceState { get => this._complianceState; set { {_complianceState = value;} } } + + /// Creates an new instance. + public ComplianceStatus() + { + + } + } + /// Compliance Status details + public partial interface IComplianceStatus : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// The compliance state of the configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The compliance state of the configuration.", + SerializedName = @"complianceState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceState { get; } + /// Datetime the configuration was last applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Datetime the configuration was last applied.", + SerializedName = @"lastConfigApplied", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastConfigApplied { get; set; } + /// Message from when the configuration was applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Message from when the configuration was applied.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + /// Level of the message. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Level of the message.", + SerializedName = @"messageLevel", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? MessageLevel { get; set; } + + } + /// Compliance Status details + internal partial interface IComplianceStatusInternal + + { + /// The compliance state of the configuration. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceState { get; set; } + /// Datetime the configuration was last applied. + global::System.DateTime? LastConfigApplied { get; set; } + /// Message from when the configuration was applied. + string Message { get; set; } + /// Level of the message. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? MessageLevel { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.json.cs new file mode 100644 index 000000000000..7db7992d990d --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ComplianceStatus.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Compliance Status details + public partial class ComplianceStatus + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ComplianceStatus(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_complianceState = If( json?.PropertyT("complianceState"), out var __jsonComplianceState) ? (string)__jsonComplianceState : (string)ComplianceState;} + {_lastConfigApplied = If( json?.PropertyT("lastConfigApplied"), out var __jsonLastConfigApplied) ? global::System.DateTime.TryParse((string)__jsonLastConfigApplied, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastConfigAppliedValue) ? __jsonLastConfigAppliedValue : LastConfigApplied : LastConfigApplied;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;} + {_messageLevel = If( json?.PropertyT("messageLevel"), out var __jsonMessageLevel) ? (string)__jsonMessageLevel : (string)MessageLevel;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new ComplianceStatus(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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._complianceState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._complianceState.ToString()) : null, "complianceState" ,container.Add ); + } + AddIf( null != this._lastConfigApplied ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._lastConfigApplied?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastConfigApplied" ,container.Add ); + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + AddIf( null != (((object)this._messageLevel)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._messageLevel.ToString()) : null, "messageLevel" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.PowerShell.cs new file mode 100644 index 000000000000..41abcda8f35a --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Error definition. + [System.ComponentModel.TypeConverter(typeof(ErrorDefinitionTypeConverter))] + public partial class ErrorDefinition + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDefinition(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.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDefinition(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDefinition(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinitionTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDefinition(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinitionTypeConverter.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.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Error definition. + [System.ComponentModel.TypeConverter(typeof(ErrorDefinitionTypeConverter))] + public partial interface IErrorDefinition + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.TypeConverter.cs new file mode 100644 index 000000000000..2707fd7769b1 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDefinitionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDefinition.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDefinition.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDefinition.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.cs new file mode 100644 index 000000000000..65af6b54300a --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.cs @@ -0,0 +1,95 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Error definition. + public partial class ErrorDefinition : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal + { + + /// Backing field for property. + private string _code; + + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] _detail; + + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Detail { get => this._detail; } + + /// Backing field for property. + private string _message; + + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal.Message { get => this._message; set { {_message = value;} } } + + /// Creates an new instance. + public ErrorDefinition() + { + + } + } + /// Error definition. + public partial interface IErrorDefinition : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Service specific error code which serves as the substatus for the HTTP error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Internal error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Detail { get; } + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Description of the error.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + + } + /// Error definition. + internal partial interface IErrorDefinitionInternal + + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + string Code { get; set; } + /// Internal error details. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Detail { get; set; } + /// Description of the error. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.json.cs new file mode 100644 index 000000000000..9cadc360e014 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorDefinition.json.cs @@ -0,0 +1,122 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Error definition. + public partial class ErrorDefinition + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDefinition(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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;} + {_detail = If( json?.PropertyT("details"), out var __jsonDetails) ? If( __jsonDetails as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition) (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinition.FromJson(__u) )) ))() : null : Detail;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new ErrorDefinition(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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.PowerShell.cs new file mode 100644 index 000000000000..5d550dcc35f2 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Error response. + [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); + + /// + /// 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.KubernetesConfiguration.Models.Api20191101Preview.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.KubernetesConfiguration.Models.Api20191101Preview.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 + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinitionTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinitionTypeConverter.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 + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinitionTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Detail = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[]) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinitionTypeConverter.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.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Error response. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.TypeConverter.cs new file mode 100644 index 000000000000..741eed61b5dd --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.cs new file mode 100644 index 000000000000..d73ea66d79bd --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.cs @@ -0,0 +1,98 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Error response. + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal + { + + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Code; } + + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition _error; + + /// Error definition. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinition()); set => this._error = value; } + + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Message; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Code = value; } + + /// Internal Acessors for Detail + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Detail = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinition()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinitionInternal)Error).Message = value; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Error response. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Service specific error code which serves as the substatus for the HTTP error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// Internal error details. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Internal error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Detail { get; } + /// Description of the error. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Description of the error.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + + } + /// Error response. + internal partial interface IErrorResponseInternal + + { + /// + /// Service specific error code which serves as the substatus for the HTTP error code. + /// + string Code { get; set; } + /// Internal error details. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition[] Detail { get; set; } + /// Error definition. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorDefinition Error { get; set; } + /// Description of the error. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.json.cs new file mode 100644 index 000000000000..7f449045da7f --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ErrorResponse.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Error response. + 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Models.Api20191101Preview.ErrorDefinition.FromJson(__jsonError) : Error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.PowerShell.cs new file mode 100644 index 000000000000..67be0d0d6003 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Properties for Helm operator. + [System.ComponentModel.TypeConverter(typeof(HelmOperatorPropertiesTypeConverter))] + public partial class HelmOperatorProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new HelmOperatorProperties(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.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new HelmOperatorProperties(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.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal HelmOperatorProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartValue = (string) content.GetValueForProperty("ChartValue",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartValue, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartVersion = (string) content.GetValueForProperty("ChartVersion",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartVersion, 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 HelmOperatorProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartValue = (string) content.GetValueForProperty("ChartValue",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartValue, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartVersion = (string) content.GetValueForProperty("ChartVersion",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)this).ChartVersion, 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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Properties for Helm operator. + [System.ComponentModel.TypeConverter(typeof(HelmOperatorPropertiesTypeConverter))] + public partial interface IHelmOperatorProperties + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.TypeConverter.cs new file mode 100644 index 000000000000..6c48479765fc --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class HelmOperatorPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return HelmOperatorProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return HelmOperatorProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return HelmOperatorProperties.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.cs new file mode 100644 index 000000000000..7bdffb5e52f1 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Properties for Helm operator. + public partial class HelmOperatorProperties : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal + { + + /// Backing field for property. + private string _chartValue; + + /// Values override for the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string ChartValue { get => this._chartValue; set => this._chartValue = value; } + + /// Backing field for property. + private string _chartVersion; + + /// Version of the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string ChartVersion { get => this._chartVersion; set => this._chartVersion = value; } + + /// Creates an new instance. + public HelmOperatorProperties() + { + + } + } + /// Properties for Helm operator. + public partial interface IHelmOperatorProperties : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// Values override for the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Values override for the operator Helm chart.", + SerializedName = @"chartValues", + PossibleTypes = new [] { typeof(string) })] + string ChartValue { get; set; } + /// Version of the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Version of the operator Helm chart.", + SerializedName = @"chartVersion", + PossibleTypes = new [] { typeof(string) })] + string ChartVersion { get; set; } + + } + /// Properties for Helm operator. + internal partial interface IHelmOperatorPropertiesInternal + + { + /// Values override for the operator Helm chart. + string ChartValue { get; set; } + /// Version of the operator Helm chart. + string ChartVersion { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.json.cs new file mode 100644 index 000000000000..6fee03891165 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/HelmOperatorProperties.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Properties for Helm operator. + public partial class HelmOperatorProperties + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new HelmOperatorProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal HelmOperatorProperties(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_chartValue = If( json?.PropertyT("chartValues"), out var __jsonChartValues) ? (string)__jsonChartValues : (string)ChartValue;} + {_chartVersion = If( json?.PropertyT("chartVersion"), out var __jsonChartVersion) ? (string)__jsonChartVersion : (string)ChartVersion;} + 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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._chartValue)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._chartValue.ToString()) : null, "chartValues" ,container.Add ); + AddIf( null != (((object)this._chartVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._chartVersion.ToString()) : null, "chartVersion" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.PowerShell.cs new file mode 100644 index 000000000000..8a1b0446f4f7 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// ARM proxy resource. + [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); + + /// + /// 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.KubernetesConfiguration.Models.Api20191101Preview.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.KubernetesConfiguration.Models.Api20191101Preview.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.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)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 ProxyResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// ARM proxy resource. + [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] + public partial interface IProxyResource + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.TypeConverter.cs new file mode 100644 index 000000000000..2bd741840546 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.cs new file mode 100644 index 000000000000..c50ab13a1eaa --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.cs @@ -0,0 +1,69 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// ARM proxy resource. + public partial class ProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.Resource(); + + /// Resource Id + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Type = value; } + + /// Resource name + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__resource).Name; } + + /// Resource type + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.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 < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// ARM proxy resource. + public partial interface IProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResource + { + + } + /// ARM proxy resource. + internal partial interface IProxyResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.json.cs new file mode 100644 index 000000000000..d84f2999ee67 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ProxyResource.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// ARM proxy resource. + 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.PowerShell.cs new file mode 100644 index 000000000000..f1ec187baa23 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// The Resource model definition. + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.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.KubernetesConfiguration.Models.Api20191101Preview.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.KubernetesConfiguration.Models.Api20191101Preview.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)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 Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The Resource model definition. + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.TypeConverter.cs new file mode 100644 index 000000000000..da36e41513c2 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.cs new file mode 100644 index 000000000000..b8f85f229d2a --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.cs @@ -0,0 +1,89 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// The Resource model definition. + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResource, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal + { + + /// Backing field for property. + private string _id; + + /// Resource Id + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Resource name + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _type; + + /// Resource type + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// The Resource model definition. + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// Resource Id + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource Id", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Resource name + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource name", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Resource type + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource type", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The Resource model definition. + internal partial interface IResourceInternal + + { + /// Resource Id + string Id { get; set; } + /// Resource name + string Name { get; set; } + /// Resource type + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.json.cs new file mode 100644 index 000000000000..e2e963b03b48 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Resource.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// The Resource model definition. + 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + 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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.PowerShell.cs new file mode 100644 index 000000000000..474b4095d00b --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.PowerShell.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Supported operation of this resource provider. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationTypeConverter))] + public partial class ResourceProviderOperation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProviderOperation(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.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProviderOperation(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.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProviderOperation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProviderOperation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Supported operation of this resource provider. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationTypeConverter))] + public partial interface IResourceProviderOperation + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.TypeConverter.cs new file mode 100644 index 000000000000..2804f3e0d449 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProviderOperationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProviderOperation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProviderOperation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProviderOperation.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.cs new file mode 100644 index 000000000000..690cb0269f14 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Supported operation of this resource provider. + public partial class ResourceProviderOperation : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay _display; + + /// Display metadata associated with the operation. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationDisplay()); set => this._display = value; } + + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Description = value; } + + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Operation = value; } + + /// Resource provider: Microsoft KubernetesConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Provider = value; } + + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationDisplay()); set { {_display = value;} } } + + /// Backing field for property. + private string _name; + + /// Operation name, in format of {provider}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public ResourceProviderOperation() + { + + } + } + /// Supported operation of this resource provider. + public partial interface IResourceProviderOperation : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description of this operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; set; } + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of operation: get, read, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; set; } + /// Resource provider: Microsoft KubernetesConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource provider: Microsoft KubernetesConfiguration.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; set; } + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; set; } + /// Operation name, in format of {provider}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Operation name, in format of {provider}/{resource}/{operation}", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Supported operation of this resource provider. + internal partial interface IResourceProviderOperationInternal + + { + /// Display metadata associated with the operation. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay Display { get; set; } + /// Description of this operation. + string DisplayDescription { get; set; } + /// Type of operation: get, read, delete, etc. + string DisplayOperation { get; set; } + /// Resource provider: Microsoft KubernetesConfiguration. + string DisplayProvider { get; set; } + /// Resource on which the operation is performed. + string DisplayResource { get; set; } + /// Operation name, in format of {provider}/{resource}/{operation} + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.json.cs new file mode 100644 index 000000000000..21ddd0ec7f53 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperation.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Supported operation of this resource provider. + public partial class ResourceProviderOperation + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new ResourceProviderOperation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceProviderOperation(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationDisplay.FromJson(__jsonDisplay) : Display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.PowerShell.cs new file mode 100644 index 000000000000..e53a54eeb763 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Display metadata associated with the operation. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationDisplayTypeConverter))] + public partial class ResourceProviderOperationDisplay + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProviderOperationDisplay(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.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProviderOperationDisplay(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.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProviderOperationDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProviderOperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Description, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Display metadata associated with the operation. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationDisplayTypeConverter))] + public partial interface IResourceProviderOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.TypeConverter.cs new file mode 100644 index 000000000000..6d8ad5fd0d68 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProviderOperationDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProviderOperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProviderOperationDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProviderOperationDisplay.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.cs new file mode 100644 index 000000000000..1a9ef0c99a34 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.cs @@ -0,0 +1,97 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Display metadata associated with the operation. + public partial class ResourceProviderOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _operation; + + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Operation { get => this._operation; set => this._operation = value; } + + /// Backing field for property. + private string _provider; + + /// Resource provider: Microsoft KubernetesConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Provider { get => this._provider; set => this._provider = value; } + + /// Backing field for property. + private string _resource; + + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Resource { get => this._resource; set => this._resource = value; } + + /// Creates an new instance. + public ResourceProviderOperationDisplay() + { + + } + } + /// Display metadata associated with the operation. + public partial interface IResourceProviderOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// Description of this operation. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description of this operation.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of operation: get, read, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; set; } + /// Resource provider: Microsoft KubernetesConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource provider: Microsoft KubernetesConfiguration.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; set; } + /// Resource on which the operation is performed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource on which the operation is performed.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; set; } + + } + /// Display metadata associated with the operation. + internal partial interface IResourceProviderOperationDisplayInternal + + { + /// Description of this operation. + string Description { get; set; } + /// Type of operation: get, read, delete, etc. + string Operation { get; set; } + /// Resource provider: Microsoft KubernetesConfiguration. + string Provider { get; set; } + /// Resource on which the operation is performed. + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.json.cs new file mode 100644 index 000000000000..e9f69405ade9 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationDisplay.json.cs @@ -0,0 +1,107 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Display metadata associated with the operation. + public partial class ResourceProviderOperationDisplay + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new ResourceProviderOperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceProviderOperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)Description;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)Operation;} + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)Provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)Resource;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.PowerShell.cs new file mode 100644 index 000000000000..da2d55082bca --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Result of the request to list operations. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationListTypeConverter))] + public partial class ResourceProviderOperationList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ResourceProviderOperationList(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.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ResourceProviderOperationList(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.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ResourceProviderOperationList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ResourceProviderOperationList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Result of the request to list operations. + [System.ComponentModel.TypeConverter(typeof(ResourceProviderOperationListTypeConverter))] + public partial interface IResourceProviderOperationList + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.TypeConverter.cs new file mode 100644 index 000000000000..d10a495794af --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceProviderOperationListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ResourceProviderOperationList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ResourceProviderOperationList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ResourceProviderOperationList.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.cs new file mode 100644 index 000000000000..883403be51a4 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.cs @@ -0,0 +1,66 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Result of the request to list operations. + public partial class ResourceProviderOperationList : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal + { + + /// Internal Acessors for NextLink + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationListInternal.NextLink { get => this._nextLink; set { {_nextLink = value;} } } + + /// Backing field for property. + private string _nextLink; + + /// URL to the next set of results, if any. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation[] _value; + + /// List of operations supported by this resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ResourceProviderOperationList() + { + + } + } + /// Result of the request to list operations. + public partial interface IResourceProviderOperationList : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// URL to the next set of results, if any. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"URL to the next set of results, if any.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; } + /// List of operations supported by this resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of operations supported by this resource provider.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation[] Value { get; set; } + + } + /// Result of the request to list operations. + internal partial interface IResourceProviderOperationListInternal + + { + /// URL to the next set of results, if any. + string NextLink { get; set; } + /// List of operations supported by this resource provider. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.json.cs new file mode 100644 index 000000000000..1451b4625c95 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/ResourceProviderOperationList.json.cs @@ -0,0 +1,114 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Result of the request to list operations. + public partial class ResourceProviderOperationList + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperationList FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new ResourceProviderOperationList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal ResourceProviderOperationList(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation) (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ResourceProviderOperation.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + } + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.PowerShell.cs new file mode 100644 index 000000000000..259c98f9a697 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Sample result definition + [System.ComponentModel.TypeConverter(typeof(ResultTypeConverter))] + public partial class Result + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Result(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.KubernetesConfiguration.Models.Api20191101Preview.IResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Result(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.KubernetesConfiguration.Models.Api20191101Preview.IResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Result(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResultInternal)this).SampleProperty = (string) content.GetValueForProperty("SampleProperty",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResultInternal)this).SampleProperty, 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 Result(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResultInternal)this).SampleProperty = (string) content.GetValueForProperty("SampleProperty",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResultInternal)this).SampleProperty, 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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Sample result definition + [System.ComponentModel.TypeConverter(typeof(ResultTypeConverter))] + public partial interface IResult + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.TypeConverter.cs new file mode 100644 index 000000000000..802e6a6c5905 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Result.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Result.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Result.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.cs new file mode 100644 index 000000000000..2efe5d087dd3 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Sample result definition + public partial class Result : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResult, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResultInternal + { + + /// Backing field for property. + private string _sampleProperty; + + /// Sample property of type string + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string SampleProperty { get => this._sampleProperty; set => this._sampleProperty = value; } + + /// Creates an new instance. + public Result() + { + + } + } + /// Sample result definition + public partial interface IResult : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// Sample property of type string + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Sample property of type string", + SerializedName = @"sampleProperty", + PossibleTypes = new [] { typeof(string) })] + string SampleProperty { get; set; } + + } + /// Sample result definition + internal partial interface IResultInternal + + { + /// Sample property of type string + string SampleProperty { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.json.cs new file mode 100644 index 000000000000..6eb00eb4436e --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/Result.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Sample result definition + public partial class Result + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new Result(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal Result(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_sampleProperty = If( json?.PropertyT("sampleProperty"), out var __jsonSampleProperty) ? (string)__jsonSampleProperty : (string)SampleProperty;} + 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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._sampleProperty)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._sampleProperty.ToString()) : null, "sampleProperty" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.PowerShell.cs new file mode 100644 index 000000000000..bae6dae9770f --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.PowerShell.cs @@ -0,0 +1,173 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// The SourceControl Configuration object. + [System.ComponentModel.TypeConverter(typeof(SourceControlConfigurationTypeConverter))] + public partial class SourceControlConfiguration + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SourceControlConfiguration(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.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SourceControlConfiguration(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.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SourceControlConfiguration(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatus = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus) content.GetValueForProperty("ComplianceStatus",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatus, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatusTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorType = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType?) content.GetValueForProperty("OperatorType",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorType, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorScope = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope?) content.GetValueForProperty("OperatorScope",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorScope, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryUrl = (string) content.GetValueForProperty("RepositoryUrl",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorNamespace = (string) content.GetValueForProperty("OperatorNamespace",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorNamespace, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorInstanceName = (string) content.GetValueForProperty("OperatorInstanceName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorInstanceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).EnableHelmOperator = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator?) content.GetValueForProperty("EnableHelmOperator",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).EnableHelmOperator, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorProperty = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties) content.GetValueForProperty("HelmOperatorProperty",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorProperty, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryPublicKey = (string) content.GetValueForProperty("RepositoryPublicKey",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryPublicKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorParam = (string) content.GetValueForProperty("OperatorParam",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorParam, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusComplianceState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState?) content.GetValueForProperty("ComplianceStatusComplianceState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusComplianceState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessage = (string) content.GetValueForProperty("ComplianceStatusMessage",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessage, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessageLevel = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel?) content.GetValueForProperty("ComplianceStatusMessageLevel",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessageLevel, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartValue = (string) content.GetValueForProperty("HelmOperatorPropertyChartValue",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartValue, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartVersion = (string) content.GetValueForProperty("HelmOperatorPropertyChartVersion",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusLastConfigApplied = (global::System.DateTime?) content.GetValueForProperty("ComplianceStatusLastConfigApplied",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusLastConfigApplied, (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 SourceControlConfiguration(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatus = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus) content.GetValueForProperty("ComplianceStatus",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatus, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatusTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorType = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType?) content.GetValueForProperty("OperatorType",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorType, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorScope = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope?) content.GetValueForProperty("OperatorScope",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorScope, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryUrl = (string) content.GetValueForProperty("RepositoryUrl",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorNamespace = (string) content.GetValueForProperty("OperatorNamespace",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorNamespace, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorInstanceName = (string) content.GetValueForProperty("OperatorInstanceName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorInstanceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).EnableHelmOperator = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator?) content.GetValueForProperty("EnableHelmOperator",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).EnableHelmOperator, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorProperty = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties) content.GetValueForProperty("HelmOperatorProperty",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorProperty, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryPublicKey = (string) content.GetValueForProperty("RepositoryPublicKey",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).RepositoryPublicKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorParam = (string) content.GetValueForProperty("OperatorParam",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).OperatorParam, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusComplianceState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState?) content.GetValueForProperty("ComplianceStatusComplianceState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusComplianceState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessage = (string) content.GetValueForProperty("ComplianceStatusMessage",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessage, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessageLevel = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel?) content.GetValueForProperty("ComplianceStatusMessageLevel",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusMessageLevel, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartValue = (string) content.GetValueForProperty("HelmOperatorPropertyChartValue",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartValue, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartVersion = (string) content.GetValueForProperty("HelmOperatorPropertyChartVersion",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).HelmOperatorPropertyChartVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusLastConfigApplied = (global::System.DateTime?) content.GetValueForProperty("ComplianceStatusLastConfigApplied",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal)this).ComplianceStatusLastConfigApplied, (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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The SourceControl Configuration object. + [System.ComponentModel.TypeConverter(typeof(SourceControlConfigurationTypeConverter))] + public partial interface ISourceControlConfiguration + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.TypeConverter.cs new file mode 100644 index 000000000000..880e6fad8c2e --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SourceControlConfigurationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SourceControlConfiguration.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SourceControlConfiguration.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SourceControlConfiguration.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.cs new file mode 100644 index 000000000000..37522f44346e --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.cs @@ -0,0 +1,325 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// The SourceControl Configuration object. + public partial class SourceControlConfiguration : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ProxyResource(); + + /// The compliance state of the configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceStatusComplianceState { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusComplianceState; } + + /// Datetime the configuration was last applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public global::System.DateTime? ComplianceStatusLastConfigApplied { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusLastConfigApplied; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusLastConfigApplied = value; } + + /// Message from when the configuration was applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string ComplianceStatusMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusMessage; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusMessage = value; } + + /// Level of the message. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? ComplianceStatusMessageLevel { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusMessageLevel; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusMessageLevel = value; } + + /// Option to enable Helm Operator for this git configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator? EnableHelmOperator { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).EnableHelmOperator; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).EnableHelmOperator = value; } + + /// Values override for the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string HelmOperatorPropertyChartValue { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).HelmOperatorPropertyChartValue; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).HelmOperatorPropertyChartValue = value; } + + /// Version of the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string HelmOperatorPropertyChartVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).HelmOperatorPropertyChartVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).HelmOperatorPropertyChartVersion = value; } + + /// Resource Id + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Name = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Type = value; } + + /// Internal Acessors for ComplianceStatus + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal.ComplianceStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatus = value; } + + /// Internal Acessors for ComplianceStatusComplianceState + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal.ComplianceStatusComplianceState { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusComplianceState; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ComplianceStatusComplianceState = value; } + + /// Internal Acessors for HelmOperatorProperty + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal.HelmOperatorProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).HelmOperatorProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).HelmOperatorProperty = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for RepositoryPublicKey + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationInternal.RepositoryPublicKey { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).RepositoryPublicKey; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).RepositoryPublicKey = value; } + + /// Resource name + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Name; } + + /// Instance name of the operator - identifying the specific configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string OperatorInstanceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorInstanceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorInstanceName = value; } + + /// + /// The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period + /// only. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string OperatorNamespace { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorNamespace; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorNamespace = value; } + + /// Any Parameters for the Operator instance in string format. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string OperatorParam { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorParam; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorParam = value; } + + /// Scope at which the operator will be installed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope? OperatorScope { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorScope; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorScope = value; } + + /// Type of the operator + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType? OperatorType { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorType; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).OperatorType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties _property; + + /// Properties to create a Source Control Configuration resource + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationProperties()); set => this._property = value; } + + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).ProvisioningState; } + + /// + /// Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string RepositoryPublicKey { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).RepositoryPublicKey; } + + /// Url of the SourceControl Repository. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string RepositoryUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).RepositoryUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)Property).RepositoryUrl = value; } + + /// Resource type + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public SourceControlConfiguration() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// The SourceControl Configuration object. + public partial interface ISourceControlConfiguration : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResource + { + /// The compliance state of the configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The compliance state of the configuration.", + SerializedName = @"complianceState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceStatusComplianceState { get; } + /// Datetime the configuration was last applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Datetime the configuration was last applied.", + SerializedName = @"lastConfigApplied", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? ComplianceStatusLastConfigApplied { get; set; } + /// Message from when the configuration was applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Message from when the configuration was applied.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string ComplianceStatusMessage { get; set; } + /// Level of the message. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Level of the message.", + SerializedName = @"messageLevel", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? ComplianceStatusMessageLevel { get; set; } + /// Option to enable Helm Operator for this git configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Option to enable Helm Operator for this git configuration.", + SerializedName = @"enableHelmOperator", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator? EnableHelmOperator { get; set; } + /// Values override for the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Values override for the operator Helm chart.", + SerializedName = @"chartValues", + PossibleTypes = new [] { typeof(string) })] + string HelmOperatorPropertyChartValue { get; set; } + /// Version of the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Version of the operator Helm chart.", + SerializedName = @"chartVersion", + PossibleTypes = new [] { typeof(string) })] + string HelmOperatorPropertyChartVersion { get; set; } + /// Instance name of the operator - identifying the specific configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Instance name of the operator - identifying the specific configuration.", + SerializedName = @"operatorInstanceName", + PossibleTypes = new [] { typeof(string) })] + string OperatorInstanceName { get; set; } + /// + /// The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period + /// only. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.", + SerializedName = @"operatorNamespace", + PossibleTypes = new [] { typeof(string) })] + string OperatorNamespace { get; set; } + /// Any Parameters for the Operator instance in string format. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Any Parameters for the Operator instance in string format.", + SerializedName = @"operatorParams", + PossibleTypes = new [] { typeof(string) })] + string OperatorParam { get; set; } + /// Scope at which the operator will be installed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Scope at which the operator will be installed.", + SerializedName = @"operatorScope", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope? OperatorScope { get; set; } + /// Type of the operator + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of the operator", + SerializedName = @"operatorType", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType? OperatorType { get; set; } + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the resource provider.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? ProvisioningState { get; } + /// + /// Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user).", + SerializedName = @"repositoryPublicKey", + PossibleTypes = new [] { typeof(string) })] + string RepositoryPublicKey { get; } + /// Url of the SourceControl Repository. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Url of the SourceControl Repository.", + SerializedName = @"repositoryUrl", + PossibleTypes = new [] { typeof(string) })] + string RepositoryUrl { get; set; } + + } + /// The SourceControl Configuration object. + internal partial interface ISourceControlConfigurationInternal : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IProxyResourceInternal + { + /// Compliance Status of the Configuration + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus ComplianceStatus { get; set; } + /// The compliance state of the configuration. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceStatusComplianceState { get; set; } + /// Datetime the configuration was last applied. + global::System.DateTime? ComplianceStatusLastConfigApplied { get; set; } + /// Message from when the configuration was applied. + string ComplianceStatusMessage { get; set; } + /// Level of the message. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? ComplianceStatusMessageLevel { get; set; } + /// Option to enable Helm Operator for this git configuration. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator? EnableHelmOperator { get; set; } + /// Properties for Helm operator. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties HelmOperatorProperty { get; set; } + /// Values override for the operator Helm chart. + string HelmOperatorPropertyChartValue { get; set; } + /// Version of the operator Helm chart. + string HelmOperatorPropertyChartVersion { get; set; } + /// Instance name of the operator - identifying the specific configuration. + string OperatorInstanceName { get; set; } + /// + /// The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period + /// only. + /// + string OperatorNamespace { get; set; } + /// Any Parameters for the Operator instance in string format. + string OperatorParam { get; set; } + /// Scope at which the operator will be installed. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope? OperatorScope { get; set; } + /// Type of the operator + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType? OperatorType { get; set; } + /// Properties to create a Source Control Configuration resource + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties Property { get; set; } + /// The provisioning state of the resource provider. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? ProvisioningState { get; set; } + /// + /// Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). + /// + string RepositoryPublicKey { get; set; } + /// Url of the SourceControl Repository. + string RepositoryUrl { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.json.cs new file mode 100644 index 000000000000..bc5f4476c62e --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfiguration.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// The SourceControl Configuration object. + public partial class SourceControlConfiguration + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new SourceControlConfiguration(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal SourceControlConfiguration(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationProperties.FromJson(__jsonProperties) : Property;} + 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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.PowerShell.cs new file mode 100644 index 000000000000..0a3bceea1303 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects + /// and a URL link to get the next set of results. + /// + [System.ComponentModel.TypeConverter(typeof(SourceControlConfigurationListTypeConverter))] + public partial class SourceControlConfigurationList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SourceControlConfigurationList(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.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SourceControlConfigurationList(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.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SourceControlConfigurationList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SourceControlConfigurationList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).NextLink, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfigurationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects + /// and a URL link to get the next set of results. + [System.ComponentModel.TypeConverter(typeof(SourceControlConfigurationListTypeConverter))] + public partial interface ISourceControlConfigurationList + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.TypeConverter.cs new file mode 100644 index 000000000000..b83c161fffa2 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SourceControlConfigurationListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SourceControlConfigurationList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SourceControlConfigurationList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SourceControlConfigurationList.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.cs new file mode 100644 index 000000000000..d84a2e0bf1cf --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.cs @@ -0,0 +1,74 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// + /// Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects + /// and a URL link to get the next set of results. + /// + public partial class SourceControlConfigurationList : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal + { + + /// Internal Acessors for NextLink + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal.NextLink { get => this._nextLink; set { {_nextLink = value;} } } + + /// Internal Acessors for Value + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration[] Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationListInternal.Value { get => this._value; set { {_value = value;} } } + + /// Backing field for property. + private string _nextLink; + + /// URL to get the next set of configuration objects, if any. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration[] _value; + + /// List of Source Control Configurations within a Kubernetes cluster. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration[] Value { get => this._value; } + + /// Creates an new instance. + public SourceControlConfigurationList() + { + + } + } + /// Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects + /// and a URL link to get the next set of results. + public partial interface ISourceControlConfigurationList : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// URL to get the next set of configuration objects, if any. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"URL to get the next set of configuration objects, if any.", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; } + /// List of Source Control Configurations within a Kubernetes cluster. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"List of Source Control Configurations within a Kubernetes cluster.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration[] Value { get; } + + } + /// Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects + /// and a URL link to get the next set of results. + internal partial interface ISourceControlConfigurationListInternal + + { + /// URL to get the next set of configuration objects, if any. + string NextLink { get; set; } + /// List of Source Control Configurations within a Kubernetes cluster. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.json.cs new file mode 100644 index 000000000000..e498317e2bf5 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationList.json.cs @@ -0,0 +1,120 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// + /// Result of the request to list Source Control Configurations. It contains a list of SourceControlConfiguration objects + /// and a URL link to get the next set of results. + /// + public partial class SourceControlConfigurationList + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationList FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new SourceControlConfigurationList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal SourceControlConfigurationList(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)NextLink;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? If( __jsonValue as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration) (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfiguration.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.PowerShell.cs new file mode 100644 index 000000000000..3c9ffaa7e78f --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.PowerShell.cs @@ -0,0 +1,165 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// Properties to create a Source Control Configuration resource + [System.ComponentModel.TypeConverter(typeof(SourceControlConfigurationPropertiesTypeConverter))] + public partial class SourceControlConfigurationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SourceControlConfigurationProperties(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.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SourceControlConfigurationProperties(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.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SourceControlConfigurationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatus = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus) content.GetValueForProperty("ComplianceStatus",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatus, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatusTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorProperty = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties) content.GetValueForProperty("HelmOperatorProperty",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorProperty, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).EnableHelmOperator = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator?) content.GetValueForProperty("EnableHelmOperator",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).EnableHelmOperator, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorInstanceName = (string) content.GetValueForProperty("OperatorInstanceName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorInstanceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorNamespace = (string) content.GetValueForProperty("OperatorNamespace",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorNamespace, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorParam = (string) content.GetValueForProperty("OperatorParam",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorParam, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorScope = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope?) content.GetValueForProperty("OperatorScope",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorScope, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorType = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType?) content.GetValueForProperty("OperatorType",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorType, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryPublicKey = (string) content.GetValueForProperty("RepositoryPublicKey",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryPublicKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryUrl = (string) content.GetValueForProperty("RepositoryUrl",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusComplianceState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState?) content.GetValueForProperty("ComplianceStatusComplianceState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusComplianceState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessage = (string) content.GetValueForProperty("ComplianceStatusMessage",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessage, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessageLevel = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel?) content.GetValueForProperty("ComplianceStatusMessageLevel",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessageLevel, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartValue = (string) content.GetValueForProperty("HelmOperatorPropertyChartValue",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartValue, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartVersion = (string) content.GetValueForProperty("HelmOperatorPropertyChartVersion",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusLastConfigApplied = (global::System.DateTime?) content.GetValueForProperty("ComplianceStatusLastConfigApplied",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusLastConfigApplied, (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 SourceControlConfigurationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatus = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus) content.GetValueForProperty("ComplianceStatus",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatus, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatusTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorProperty = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties) content.GetValueForProperty("HelmOperatorProperty",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorProperty, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).EnableHelmOperator = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator?) content.GetValueForProperty("EnableHelmOperator",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).EnableHelmOperator, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorInstanceName = (string) content.GetValueForProperty("OperatorInstanceName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorInstanceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorNamespace = (string) content.GetValueForProperty("OperatorNamespace",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorNamespace, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorParam = (string) content.GetValueForProperty("OperatorParam",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorParam, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorScope = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope?) content.GetValueForProperty("OperatorScope",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorScope, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorType = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType?) content.GetValueForProperty("OperatorType",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).OperatorType, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ProvisioningState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState?) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ProvisioningState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryPublicKey = (string) content.GetValueForProperty("RepositoryPublicKey",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryPublicKey, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryUrl = (string) content.GetValueForProperty("RepositoryUrl",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).RepositoryUrl, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusComplianceState = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState?) content.GetValueForProperty("ComplianceStatusComplianceState",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusComplianceState, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessage = (string) content.GetValueForProperty("ComplianceStatusMessage",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessage, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessageLevel = (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel?) content.GetValueForProperty("ComplianceStatusMessageLevel",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusMessageLevel, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel.CreateFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartValue = (string) content.GetValueForProperty("HelmOperatorPropertyChartValue",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartValue, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartVersion = (string) content.GetValueForProperty("HelmOperatorPropertyChartVersion",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).HelmOperatorPropertyChartVersion, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusLastConfigApplied = (global::System.DateTime?) content.GetValueForProperty("ComplianceStatusLastConfigApplied",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal)this).ComplianceStatusLastConfigApplied, (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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Properties to create a Source Control Configuration resource + [System.ComponentModel.TypeConverter(typeof(SourceControlConfigurationPropertiesTypeConverter))] + public partial interface ISourceControlConfigurationProperties + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.TypeConverter.cs new file mode 100644 index 000000000000..a98b30992130 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.TypeConverter.cs @@ -0,0 +1,144 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SourceControlConfigurationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SourceControlConfigurationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SourceControlConfigurationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SourceControlConfigurationProperties.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/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.cs new file mode 100644 index 000000000000..1ee508d55bf5 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.cs @@ -0,0 +1,314 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Properties to create a Source Control Configuration resource + public partial class SourceControlConfigurationProperties : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus _complianceStatus; + + /// Compliance Status of the Configuration + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus ComplianceStatus { get => (this._complianceStatus = this._complianceStatus ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatus()); } + + /// The compliance state of the configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceStatusComplianceState { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).ComplianceState; } + + /// Datetime the configuration was last applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public global::System.DateTime? ComplianceStatusLastConfigApplied { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).LastConfigApplied; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).LastConfigApplied = value; } + + /// Message from when the configuration was applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string ComplianceStatusMessage { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).Message = value; } + + /// Level of the message. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? ComplianceStatusMessageLevel { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).MessageLevel; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).MessageLevel = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator? _enableHelmOperator; + + /// Option to enable Helm Operator for this git configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator? EnableHelmOperator { get => this._enableHelmOperator; set => this._enableHelmOperator = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties _helmOperatorProperty; + + /// Properties for Helm operator. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties HelmOperatorProperty { get => (this._helmOperatorProperty = this._helmOperatorProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorProperties()); set => this._helmOperatorProperty = value; } + + /// Values override for the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string HelmOperatorPropertyChartValue { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)HelmOperatorProperty).ChartValue; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)HelmOperatorProperty).ChartValue = value; } + + /// Version of the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Inlined)] + public string HelmOperatorPropertyChartVersion { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)HelmOperatorProperty).ChartVersion; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorPropertiesInternal)HelmOperatorProperty).ChartVersion = value; } + + /// Internal Acessors for ComplianceStatus + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal.ComplianceStatus { get => (this._complianceStatus = this._complianceStatus ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatus()); set { {_complianceStatus = value;} } } + + /// Internal Acessors for ComplianceStatusComplianceState + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal.ComplianceStatusComplianceState { get => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).ComplianceState; set => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatusInternal)ComplianceStatus).ComplianceState = value; } + + /// Internal Acessors for HelmOperatorProperty + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal.HelmOperatorProperty { get => (this._helmOperatorProperty = this._helmOperatorProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorProperties()); set { {_helmOperatorProperty = value;} } } + + /// Internal Acessors for ProvisioningState + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for RepositoryPublicKey + string Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationPropertiesInternal.RepositoryPublicKey { get => this._repositoryPublicKey; set { {_repositoryPublicKey = value;} } } + + /// Backing field for property. + private string _operatorInstanceName; + + /// Instance name of the operator - identifying the specific configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string OperatorInstanceName { get => this._operatorInstanceName; set => this._operatorInstanceName = value; } + + /// Backing field for property. + private string _operatorNamespace; + + /// + /// The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period + /// only. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string OperatorNamespace { get => this._operatorNamespace; set => this._operatorNamespace = value; } + + /// Backing field for property. + private string _operatorParam; + + /// Any Parameters for the Operator instance in string format. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string OperatorParam { get => this._operatorParam; set => this._operatorParam = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope? _operatorScope; + + /// Scope at which the operator will be installed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope? OperatorScope { get => this._operatorScope; set => this._operatorScope = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType? _operatorType; + + /// Type of the operator + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType? OperatorType { get => this._operatorType; set => this._operatorType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? _provisioningState; + + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _repositoryPublicKey; + + /// + /// Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string RepositoryPublicKey { get => this._repositoryPublicKey; } + + /// Backing field for property. + private string _repositoryUrl; + + /// Url of the SourceControl Repository. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string RepositoryUrl { get => this._repositoryUrl; set => this._repositoryUrl = value; } + + /// Creates an new instance. + public SourceControlConfigurationProperties() + { + + } + } + /// Properties to create a Source Control Configuration resource + public partial interface ISourceControlConfigurationProperties : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// The compliance state of the configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The compliance state of the configuration.", + SerializedName = @"complianceState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceStatusComplianceState { get; } + /// Datetime the configuration was last applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Datetime the configuration was last applied.", + SerializedName = @"lastConfigApplied", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? ComplianceStatusLastConfigApplied { get; set; } + /// Message from when the configuration was applied. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Message from when the configuration was applied.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string ComplianceStatusMessage { get; set; } + /// Level of the message. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Level of the message.", + SerializedName = @"messageLevel", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? ComplianceStatusMessageLevel { get; set; } + /// Option to enable Helm Operator for this git configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Option to enable Helm Operator for this git configuration.", + SerializedName = @"enableHelmOperator", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator? EnableHelmOperator { get; set; } + /// Values override for the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Values override for the operator Helm chart.", + SerializedName = @"chartValues", + PossibleTypes = new [] { typeof(string) })] + string HelmOperatorPropertyChartValue { get; set; } + /// Version of the operator Helm chart. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Version of the operator Helm chart.", + SerializedName = @"chartVersion", + PossibleTypes = new [] { typeof(string) })] + string HelmOperatorPropertyChartVersion { get; set; } + /// Instance name of the operator - identifying the specific configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Instance name of the operator - identifying the specific configuration.", + SerializedName = @"operatorInstanceName", + PossibleTypes = new [] { typeof(string) })] + string OperatorInstanceName { get; set; } + /// + /// The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period + /// only. + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.", + SerializedName = @"operatorNamespace", + PossibleTypes = new [] { typeof(string) })] + string OperatorNamespace { get; set; } + /// Any Parameters for the Operator instance in string format. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Any Parameters for the Operator instance in string format.", + SerializedName = @"operatorParams", + PossibleTypes = new [] { typeof(string) })] + string OperatorParam { get; set; } + /// Scope at which the operator will be installed. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Scope at which the operator will be installed.", + SerializedName = @"operatorScope", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope? OperatorScope { get; set; } + /// Type of the operator + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of the operator", + SerializedName = @"operatorType", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType? OperatorType { get; set; } + /// The provisioning state of the resource provider. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state of the resource provider.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState) })] + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? ProvisioningState { get; } + /// + /// Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user).", + SerializedName = @"repositoryPublicKey", + PossibleTypes = new [] { typeof(string) })] + string RepositoryPublicKey { get; } + /// Url of the SourceControl Repository. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Url of the SourceControl Repository.", + SerializedName = @"repositoryUrl", + PossibleTypes = new [] { typeof(string) })] + string RepositoryUrl { get; set; } + + } + /// Properties to create a Source Control Configuration resource + internal partial interface ISourceControlConfigurationPropertiesInternal + + { + /// Compliance Status of the Configuration + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IComplianceStatus ComplianceStatus { get; set; } + /// The compliance state of the configuration. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState? ComplianceStatusComplianceState { get; set; } + /// Datetime the configuration was last applied. + global::System.DateTime? ComplianceStatusLastConfigApplied { get; set; } + /// Message from when the configuration was applied. + string ComplianceStatusMessage { get; set; } + /// Level of the message. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel? ComplianceStatusMessageLevel { get; set; } + /// Option to enable Helm Operator for this git configuration. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator? EnableHelmOperator { get; set; } + /// Properties for Helm operator. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IHelmOperatorProperties HelmOperatorProperty { get; set; } + /// Values override for the operator Helm chart. + string HelmOperatorPropertyChartValue { get; set; } + /// Version of the operator Helm chart. + string HelmOperatorPropertyChartVersion { get; set; } + /// Instance name of the operator - identifying the specific configuration. + string OperatorInstanceName { get; set; } + /// + /// The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period + /// only. + /// + string OperatorNamespace { get; set; } + /// Any Parameters for the Operator instance in string format. + string OperatorParam { get; set; } + /// Scope at which the operator will be installed. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope? OperatorScope { get; set; } + /// Type of the operator + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType? OperatorType { get; set; } + /// The provisioning state of the resource provider. + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState? ProvisioningState { get; set; } + /// + /// Public Key associated with this SourceControl configuration (either generated within the cluster or provided by the user). + /// + string RepositoryPublicKey { get; set; } + /// Url of the SourceControl Repository. + string RepositoryUrl { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.json.cs b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.json.cs new file mode 100644 index 000000000000..78ae06a52f2a --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/Api20191101Preview/SourceControlConfigurationProperties.json.cs @@ -0,0 +1,131 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Properties to create a Source Control Configuration resource + public partial class SourceControlConfigurationProperties + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfigurationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new SourceControlConfigurationProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal SourceControlConfigurationProperties(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_complianceStatus = If( json?.PropertyT("complianceStatus"), out var __jsonComplianceStatus) ? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ComplianceStatus.FromJson(__jsonComplianceStatus) : ComplianceStatus;} + {_helmOperatorProperty = If( json?.PropertyT("helmOperatorProperties"), out var __jsonHelmOperatorProperties) ? Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.HelmOperatorProperties.FromJson(__jsonHelmOperatorProperties) : HelmOperatorProperty;} + {_enableHelmOperator = If( json?.PropertyT("enableHelmOperator"), out var __jsonEnableHelmOperator) ? (string)__jsonEnableHelmOperator : (string)EnableHelmOperator;} + {_operatorInstanceName = If( json?.PropertyT("operatorInstanceName"), out var __jsonOperatorInstanceName) ? (string)__jsonOperatorInstanceName : (string)OperatorInstanceName;} + {_operatorNamespace = If( json?.PropertyT("operatorNamespace"), out var __jsonOperatorNamespace) ? (string)__jsonOperatorNamespace : (string)OperatorNamespace;} + {_operatorParam = If( json?.PropertyT("operatorParams"), out var __jsonOperatorParams) ? (string)__jsonOperatorParams : (string)OperatorParam;} + {_operatorScope = If( json?.PropertyT("operatorScope"), out var __jsonOperatorScope) ? (string)__jsonOperatorScope : (string)OperatorScope;} + {_operatorType = If( json?.PropertyT("operatorType"), out var __jsonOperatorType) ? (string)__jsonOperatorType : (string)OperatorType;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + {_repositoryPublicKey = If( json?.PropertyT("repositoryPublicKey"), out var __jsonRepositoryPublicKey) ? (string)__jsonRepositoryPublicKey : (string)RepositoryPublicKey;} + {_repositoryUrl = If( json?.PropertyT("repositoryUrl"), out var __jsonRepositoryUrl) ? (string)__jsonRepositoryUrl : (string)RepositoryUrl;} + 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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != this._complianceStatus ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) this._complianceStatus.ToJson(null,serializationMode) : null, "complianceStatus" ,container.Add ); + } + AddIf( null != this._helmOperatorProperty ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) this._helmOperatorProperty.ToJson(null,serializationMode) : null, "helmOperatorProperties" ,container.Add ); + AddIf( null != (((object)this._enableHelmOperator)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._enableHelmOperator.ToString()) : null, "enableHelmOperator" ,container.Add ); + AddIf( null != (((object)this._operatorInstanceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._operatorInstanceName.ToString()) : null, "operatorInstanceName" ,container.Add ); + AddIf( null != (((object)this._operatorNamespace)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._operatorNamespace.ToString()) : null, "operatorNamespace" ,container.Add ); + AddIf( null != (((object)this._operatorParam)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._operatorParam.ToString()) : null, "operatorParams" ,container.Add ); + AddIf( null != (((object)this._operatorScope)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._operatorScope.ToString()) : null, "operatorScope" ,container.Add ); + AddIf( null != (((object)this._operatorType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._operatorType.ToString()) : null, "operatorType" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._repositoryPublicKey)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._repositoryPublicKey.ToString()) : null, "repositoryPublicKey" ,container.Add ); + } + AddIf( null != (((object)this._repositoryUrl)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._repositoryUrl.ToString()) : null, "repositoryUrl" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.PowerShell.cs b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.PowerShell.cs new file mode 100644 index 000000000000..f214235ff017 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.PowerShell.cs @@ -0,0 +1,148 @@ +// 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.KubernetesConfiguration.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(KubernetesConfigurationIdentityTypeConverter))] + public partial class KubernetesConfigurationIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new KubernetesConfigurationIdentity(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.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new KubernetesConfigurationIdentity(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.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal KubernetesConfigurationIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterResourceName = (string) content.GetValueForProperty("ClusterResourceName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterResourceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterRp = (string) content.GetValueForProperty("ClusterRp",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterRp, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SourceControlConfigurationName = (string) content.GetValueForProperty("SourceControlConfigurationName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SourceControlConfigurationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal KubernetesConfigurationIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterName = (string) content.GetValueForProperty("ClusterName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterResourceName = (string) content.GetValueForProperty("ClusterResourceName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterResourceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterRp = (string) content.GetValueForProperty("ClusterRp",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ClusterRp, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SourceControlConfigurationName = (string) content.GetValueForProperty("SourceControlConfigurationName",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SourceControlConfigurationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal)this).SubscriptionId, 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.KubernetesConfiguration.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(KubernetesConfigurationIdentityTypeConverter))] + public partial interface IKubernetesConfigurationIdentity + + { + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.TypeConverter.cs new file mode 100644 index 000000000000..0d1a3f1dd693 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.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.KubernetesConfiguration.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class KubernetesConfigurationIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity 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 KubernetesConfigurationIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return KubernetesConfigurationIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return KubernetesConfigurationIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return KubernetesConfigurationIdentity.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/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.cs b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.cs new file mode 100644 index 000000000000..82b33c4de8f7 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.cs @@ -0,0 +1,174 @@ +// 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.KubernetesConfiguration.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + public partial class KubernetesConfigurationIdentity : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentityInternal + { + + /// Backing field for property. + private string _clusterName; + + /// The name of the kubernetes cluster. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private string _clusterResourceName; + + /// + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S + /// clusters). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string ClusterResourceName { get => this._clusterResourceName; set => this._clusterResourceName = value; } + + /// Backing field for property. + private string _clusterRp; + + /// + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S + /// clusters). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string ClusterRp { get => this._clusterRp; set => this._clusterRp = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _sourceControlConfigurationName; + + /// Name of the Source Control Configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string SourceControlConfigurationName { get => this._sourceControlConfigurationName; set => this._sourceControlConfigurationName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public KubernetesConfigurationIdentity() + { + + } + } + public partial interface IKubernetesConfigurationIdentity : + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IJsonSerializable + { + /// The name of the kubernetes cluster. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the kubernetes cluster.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + string ClusterName { get; set; } + /// + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S + /// clusters). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).", + SerializedName = @"clusterResourceName", + PossibleTypes = new [] { typeof(string) })] + string ClusterResourceName { get; set; } + /// + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S + /// clusters). + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).", + SerializedName = @"clusterRp", + PossibleTypes = new [] { typeof(string) })] + string ClusterRp { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The name of the resource group. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroupName { get; set; } + /// Name of the Source Control Configuration. + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the Source Control Configuration.", + SerializedName = @"sourceControlConfigurationName", + PossibleTypes = new [] { typeof(string) })] + string SourceControlConfigurationName { get; set; } + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface IKubernetesConfigurationIdentityInternal + + { + /// The name of the kubernetes cluster. + string ClusterName { get; set; } + /// + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S + /// clusters). + /// + string ClusterResourceName { get; set; } + /// + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S + /// clusters). + /// + string ClusterRp { get; set; } + /// Resource identity path + string Id { get; set; } + /// The name of the resource group. + string ResourceGroupName { get; set; } + /// Name of the Source Control Configuration. + string SourceControlConfigurationName { get; set; } + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.json.cs b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.json.cs new file mode 100644 index 000000000000..e53c55624446 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Models/KubernetesConfigurationIdentity.json.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. +// 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.KubernetesConfiguration.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + public partial class KubernetesConfigurationIdentity + { + + /// + /// 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.KubernetesConfiguration.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json ? new KubernetesConfigurationIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject instance to deserialize from. + internal KubernetesConfigurationIdentity(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_clusterName = If( json?.PropertyT("clusterName"), out var __jsonClusterName) ? (string)__jsonClusterName : (string)ClusterName;} + {_clusterResourceName = If( json?.PropertyT("clusterResourceName"), out var __jsonClusterResourceName) ? (string)__jsonClusterResourceName : (string)ClusterResourceName;} + {_clusterRp = If( json?.PropertyT("clusterRp"), out var __jsonClusterRp) ? (string)__jsonClusterRp : (string)ClusterRp;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)ResourceGroupName;} + {_sourceControlConfigurationName = If( json?.PropertyT("sourceControlConfigurationName"), out var __jsonSourceControlConfigurationName) ? (string)__jsonSourceControlConfigurationName : (string)SourceControlConfigurationName;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)SubscriptionId;} + 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.KubernetesConfiguration.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._clusterName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._clusterName.ToString()) : null, "clusterName" ,container.Add ); + AddIf( null != (((object)this._clusterResourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._clusterResourceName.ToString()) : null, "clusterResourceName" ,container.Add ); + AddIf( null != (((object)this._clusterRp)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._clusterRp.ToString()) : null, "clusterRp" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._sourceControlConfigurationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._sourceControlConfigurationName.ToString()) : null, "sourceControlConfigurationName" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/ComplianceState.Completer.cs b/src/KubernetesConfiguration/generated/api/Support/ComplianceState.Completer.cs new file mode 100644 index 000000000000..80373bd32bf2 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/ComplianceState.Completer.cs @@ -0,0 +1,51 @@ +// 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.KubernetesConfiguration.Support +{ + + /// Argument completer implementation for ComplianceState. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceStateTypeConverter))] + public partial struct ComplianceState : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Pending".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Pending", "Pending", global::System.Management.Automation.CompletionResultType.ParameterValue, "Pending"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Compliant".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Compliant", "Compliant", global::System.Management.Automation.CompletionResultType.ParameterValue, "Compliant"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Noncompliant".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Noncompliant", "Noncompliant", global::System.Management.Automation.CompletionResultType.ParameterValue, "Noncompliant"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Installed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Installed", "Installed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Installed"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Failed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Failed", "Failed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Failed"); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/ComplianceState.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Support/ComplianceState.TypeConverter.cs new file mode 100644 index 000000000000..fe729f47acda --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/ComplianceState.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support +{ + + /// TypeConverter implementation for ComplianceState. + public partial class ComplianceStateTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ComplianceState.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/ComplianceState.cs b/src/KubernetesConfiguration/generated/api/Support/ComplianceState.cs new file mode 100644 index 000000000000..6fe263b31c9b --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/ComplianceState.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. +// 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.KubernetesConfiguration.Support +{ + + public partial struct ComplianceState : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState Compliant = @"Compliant"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState Failed = @"Failed"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState Installed = @"Installed"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState Noncompliant = @"Noncompliant"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState Pending = @"Pending"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Creates an instance of the + /// the value to create an instance for. + private ComplianceState(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Conversion from arbitrary object to ComplianceState + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ComplianceState(System.Convert.ToString(value)); + } + + /// Compares values of enum type ComplianceState + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ComplianceState (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ComplianceState && Equals((ComplianceState)obj); + } + + /// Returns hashCode for enum ComplianceState + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Returns string representation for ComplianceState + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ComplianceState + /// the value to convert to an instance of . + + public static implicit operator ComplianceState(string value) + { + return new ComplianceState(value); + } + + /// Implicit operator to convert ComplianceState to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState e) + { + return e._value; + } + + /// Overriding != operator for enum ComplianceState + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ComplianceState + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ComplianceState e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.Completer.cs b/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.Completer.cs new file mode 100644 index 000000000000..c17cd718c9ae --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.Completer.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. +// 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.KubernetesConfiguration.Support +{ + + /// Argument completer implementation for EnableHelmOperator. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperatorTypeConverter))] + public partial struct EnableHelmOperator : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "true".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("true", "true", global::System.Management.Automation.CompletionResultType.ParameterValue, "true"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "false".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("false", "false", global::System.Management.Automation.CompletionResultType.ParameterValue, "false"); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.TypeConverter.cs new file mode 100644 index 000000000000..3bdfca875029 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support +{ + + /// TypeConverter implementation for EnableHelmOperator. + public partial class EnableHelmOperatorTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => EnableHelmOperator.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.cs b/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.cs new file mode 100644 index 000000000000..bf63788324b3 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/EnableHelmOperator.cs @@ -0,0 +1,97 @@ +// 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.KubernetesConfiguration.Support +{ + + public partial struct EnableHelmOperator : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator False = @"false"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator True = @"true"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to EnableHelmOperator + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new EnableHelmOperator(System.Convert.ToString(value)); + } + + /// Creates an instance of the + /// the value to create an instance for. + private EnableHelmOperator(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Compares values of enum type EnableHelmOperator + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type EnableHelmOperator (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is EnableHelmOperator && Equals((EnableHelmOperator)obj); + } + + /// Returns hashCode for enum EnableHelmOperator + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Returns string representation for EnableHelmOperator + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to EnableHelmOperator + /// the value to convert to an instance of . + + public static implicit operator EnableHelmOperator(string value) + { + return new EnableHelmOperator(value); + } + + /// Implicit operator to convert EnableHelmOperator to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator e) + { + return e._value; + } + + /// Overriding != operator for enum EnableHelmOperator + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum EnableHelmOperator + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/MessageLevel.Completer.cs b/src/KubernetesConfiguration/generated/api/Support/MessageLevel.Completer.cs new file mode 100644 index 000000000000..644b8033828e --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/MessageLevel.Completer.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. +// 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.KubernetesConfiguration.Support +{ + + /// Argument completer implementation for MessageLevel. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevelTypeConverter))] + public partial struct MessageLevel : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Error".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Error", "Error", global::System.Management.Automation.CompletionResultType.ParameterValue, "Error"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Warning".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Warning", "Warning", global::System.Management.Automation.CompletionResultType.ParameterValue, "Warning"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Information".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Information", "Information", global::System.Management.Automation.CompletionResultType.ParameterValue, "Information"); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/MessageLevel.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Support/MessageLevel.TypeConverter.cs new file mode 100644 index 000000000000..57f095ae3ac4 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/MessageLevel.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support +{ + + /// TypeConverter implementation for MessageLevel. + public partial class MessageLevelTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => MessageLevel.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/MessageLevel.cs b/src/KubernetesConfiguration/generated/api/Support/MessageLevel.cs new file mode 100644 index 000000000000..08615a12c72d --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/MessageLevel.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support +{ + + public partial struct MessageLevel : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel Error = @"Error"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel Information = @"Information"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel Warning = @"Warning"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to MessageLevel + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new MessageLevel(System.Convert.ToString(value)); + } + + /// Compares values of enum type MessageLevel + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type MessageLevel (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is MessageLevel && Equals((MessageLevel)obj); + } + + /// Returns hashCode for enum MessageLevel + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private MessageLevel(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for MessageLevel + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to MessageLevel + /// the value to convert to an instance of . + + public static implicit operator MessageLevel(string value) + { + return new MessageLevel(value); + } + + /// Implicit operator to convert MessageLevel to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel e) + { + return e._value; + } + + /// Overriding != operator for enum MessageLevel + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum MessageLevel + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/OperatorScope.Completer.cs b/src/KubernetesConfiguration/generated/api/Support/OperatorScope.Completer.cs new file mode 100644 index 000000000000..ed98f87e0976 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/OperatorScope.Completer.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. +// 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.KubernetesConfiguration.Support +{ + + /// Argument completer implementation for OperatorScope. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScopeTypeConverter))] + public partial struct OperatorScope : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "cluster".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("cluster", "cluster", global::System.Management.Automation.CompletionResultType.ParameterValue, "cluster"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "namespace".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("namespace", "namespace", global::System.Management.Automation.CompletionResultType.ParameterValue, "namespace"); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/OperatorScope.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Support/OperatorScope.TypeConverter.cs new file mode 100644 index 000000000000..cafae6f1540a --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/OperatorScope.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support +{ + + /// TypeConverter implementation for OperatorScope. + public partial class OperatorScopeTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => OperatorScope.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/OperatorScope.cs b/src/KubernetesConfiguration/generated/api/Support/OperatorScope.cs new file mode 100644 index 000000000000..fedb075e6944 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/OperatorScope.cs @@ -0,0 +1,97 @@ +// 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.KubernetesConfiguration.Support +{ + + public partial struct OperatorScope : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope Cluster = @"cluster"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope Namespace = @"namespace"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to OperatorScope + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new OperatorScope(System.Convert.ToString(value)); + } + + /// Compares values of enum type OperatorScope + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type OperatorScope (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is OperatorScope && Equals((OperatorScope)obj); + } + + /// Returns hashCode for enum OperatorScope + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private OperatorScope(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for OperatorScope + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to OperatorScope + /// the value to convert to an instance of . + + public static implicit operator OperatorScope(string value) + { + return new OperatorScope(value); + } + + /// Implicit operator to convert OperatorScope to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope e) + { + return e._value; + } + + /// Overriding != operator for enum OperatorScope + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum OperatorScope + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/OperatorType.Completer.cs b/src/KubernetesConfiguration/generated/api/Support/OperatorType.Completer.cs new file mode 100644 index 000000000000..9332ec034bea --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/OperatorType.Completer.cs @@ -0,0 +1,35 @@ +// 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.KubernetesConfiguration.Support +{ + + /// Argument completer implementation for OperatorType. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorTypeTypeConverter))] + public partial struct OperatorType : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Flux".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Flux", "Flux", global::System.Management.Automation.CompletionResultType.ParameterValue, "Flux"); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/OperatorType.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Support/OperatorType.TypeConverter.cs new file mode 100644 index 000000000000..040eb5aad040 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/OperatorType.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support +{ + + /// TypeConverter implementation for OperatorType. + public partial class OperatorTypeTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => OperatorType.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/OperatorType.cs b/src/KubernetesConfiguration/generated/api/Support/OperatorType.cs new file mode 100644 index 000000000000..fb5b5ddc61d8 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/OperatorType.cs @@ -0,0 +1,95 @@ +// 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.KubernetesConfiguration.Support +{ + + public partial struct OperatorType : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType Flux = @"Flux"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to OperatorType + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new OperatorType(System.Convert.ToString(value)); + } + + /// Compares values of enum type OperatorType + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type OperatorType (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is OperatorType && Equals((OperatorType)obj); + } + + /// Returns hashCode for enum OperatorType + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private OperatorType(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for OperatorType + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to OperatorType + /// the value to convert to an instance of . + + public static implicit operator OperatorType(string value) + { + return new OperatorType(value); + } + + /// Implicit operator to convert OperatorType to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType e) + { + return e._value; + } + + /// Overriding != operator for enum OperatorType + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum OperatorType + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.Completer.cs b/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.Completer.cs new file mode 100644 index 000000000000..5be7ef20b555 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.Completer.cs @@ -0,0 +1,51 @@ +// 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.KubernetesConfiguration.Support +{ + + /// Argument completer implementation for ProvisioningState. + [System.ComponentModel.TypeConverter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningStateTypeConverter))] + public partial struct ProvisioningState : + System.Management.Automation.IArgumentCompleter + { + + /// + /// Implementations of this function are called by PowerShell to complete arguments. + /// + /// The name of the command that needs argument completion. + /// The name of the parameter that needs argument completion. + /// The (possibly empty) word being completed. + /// The command ast in case it is needed for completion. + /// This parameter is similar to $PSBoundParameters, except that sometimes PowerShell cannot + /// or will not attempt to evaluate an argument, in which case you may need to use commandAst. + /// + /// A collection of completion results, most like with ResultType set to ParameterValue. + /// + public global::System.Collections.Generic.IEnumerable CompleteArgument(global::System.String commandName, global::System.String parameterName, global::System.String wordToComplete, global::System.Management.Automation.Language.CommandAst commandAst, global::System.Collections.IDictionary fakeBoundParameters) + { + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Accepted".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Accepted", "Accepted", global::System.Management.Automation.CompletionResultType.ParameterValue, "Accepted"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Deleting".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Deleting", "Deleting", global::System.Management.Automation.CompletionResultType.ParameterValue, "Deleting"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Running".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Running", "Running", global::System.Management.Automation.CompletionResultType.ParameterValue, "Running"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Succeeded".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Succeeded", "Succeeded", global::System.Management.Automation.CompletionResultType.ParameterValue, "Succeeded"); + } + if (global::System.String.IsNullOrEmpty(wordToComplete) || "Failed".StartsWith(wordToComplete, global::System.StringComparison.InvariantCultureIgnoreCase)) + { + yield return new global::System.Management.Automation.CompletionResult("Failed", "Failed", global::System.Management.Automation.CompletionResultType.ParameterValue, "Failed"); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.TypeConverter.cs b/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.TypeConverter.cs new file mode 100644 index 000000000000..efb75d028240 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.TypeConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support +{ + + /// TypeConverter implementation for ProvisioningState. + public partial class ProvisioningStateTypeConverter : + global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ProvisioningState.CreateFrom(sourceValue); + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.cs b/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.cs new file mode 100644 index 000000000000..16fa986ea165 --- /dev/null +++ b/src/KubernetesConfiguration/generated/api/Support/ProvisioningState.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. +// 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.KubernetesConfiguration.Support +{ + + public partial struct ProvisioningState : + System.IEquatable + { + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState Accepted = @"Accepted"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState Deleting = @"Deleting"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState Failed = @"Failed"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState Running = @"Running"; + + public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState Succeeded = @"Succeeded"; + + /// the value for an instance of the Enum. + private string _value { get; set; } + + /// Conversion from arbitrary object to ProvisioningState + /// the value to convert to an instance of . + internal static object CreateFrom(object value) + { + return new ProvisioningState(System.Convert.ToString(value)); + } + + /// Compares values of enum type ProvisioningState + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState e) + { + return _value.Equals(e._value); + } + + /// Compares values of enum type ProvisioningState (override for Object) + /// the value to compare against this instance. + /// true if the two instances are equal to the same value + public override bool Equals(object obj) + { + return obj is ProvisioningState && Equals((ProvisioningState)obj); + } + + /// Returns hashCode for enum ProvisioningState + /// The hashCode of the value + public override int GetHashCode() + { + return this._value.GetHashCode(); + } + + /// Creates an instance of the + /// the value to create an instance for. + private ProvisioningState(string underlyingValue) + { + this._value = underlyingValue; + } + + /// Returns string representation for ProvisioningState + /// A string for this value. + public override string ToString() + { + return this._value; + } + + /// Implicit operator to convert string to ProvisioningState + /// the value to convert to an instance of . + + public static implicit operator ProvisioningState(string value) + { + return new ProvisioningState(value); + } + + /// Implicit operator to convert ProvisioningState to string + /// the value to convert to an instance of . + + public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState e) + { + return e._value; + } + + /// Overriding != operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are not equal to the same value + public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState e2) + { + return !e2.Equals(e1); + } + + /// Overriding == operator for enum ProvisioningState + /// the value to compare against + /// the value to compare against + /// true if the two instances are equal to the same value + public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.ProvisioningState e2) + { + return e2.Equals(e1); + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_Get.cs b/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_Get.cs new file mode 100644 index 000000000000..aa4dff37af4c --- /dev/null +++ b/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_Get.cs @@ -0,0 +1,449 @@ +// 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.KubernetesConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Gets details of the Source Control Configuration. + /// + /// [OpenAPI] SourceControlConfigurations_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzKubernetesConfiguration_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration))] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Description(@"Gets details of the Source Control Configuration.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Generated] + public partial class GetAzKubernetesConfiguration_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration Client => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the kubernetes cluster. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the kubernetes cluster.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the kubernetes cluster.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private string _clusterRp; + + /// + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).", + SerializedName = @"clusterRp", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterRp { get => this._clusterRp; set => this._clusterRp = value; } + + /// Backing field for property. + private string _clusterType; + + /// + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).", + SerializedName = @"clusterResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterType { get => this._clusterType; set => this._clusterType = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Source Control Configuration. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Source Control Configuration.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Source Control Configuration.", + SerializedName = @"sourceControlConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SourceControlConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzKubernetesConfiguration_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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SourceControlConfigurationsGet(SubscriptionId, ResourceGroupName, ClusterRp, ClusterType, ClusterName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterRp=ClusterRp,ClusterType=ClusterType,ClusterName=ClusterName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_GetViaIdentity.cs b/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_GetViaIdentity.cs new file mode 100644 index 000000000000..3ffc9b4c139e --- /dev/null +++ b/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_GetViaIdentity.cs @@ -0,0 +1,389 @@ +// 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.KubernetesConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Gets details of the Source Control Configuration. + /// + /// [OpenAPI] SourceControlConfigurations_Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzKubernetesConfiguration_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration))] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Description(@"Gets details of the Source Control Configuration.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Generated] + public partial class GetAzKubernetesConfiguration_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration Client => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzKubernetesConfiguration_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SourceControlConfigurationsGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterRp) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterRp"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SourceControlConfigurationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SourceControlConfigurationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SourceControlConfigurationsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ClusterRp ?? null, InputObject.ClusterResourceName ?? null, InputObject.ClusterName ?? null, InputObject.SourceControlConfigurationName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_List.cs b/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_List.cs new file mode 100644 index 000000000000..8fe87d840533 --- /dev/null +++ b/src/KubernetesConfiguration/generated/cmdlets/GetAzKubernetesConfiguration_List.cs @@ -0,0 +1,445 @@ +// 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.KubernetesConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// List all Source Control Configurations. + /// + /// [OpenAPI] SourceControlConfigurations_List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzKubernetesConfiguration_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration))] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Description(@"List all Source Control Configurations.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Generated] + public partial class GetAzKubernetesConfiguration_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration Client => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the kubernetes cluster. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the kubernetes cluster.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the kubernetes cluster.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private string _clusterRp; + + /// + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).", + SerializedName = @"clusterRp", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterRp { get => this._clusterRp; set => this._clusterRp = value; } + + /// Backing field for property. + private string _clusterType; + + /// + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).", + SerializedName = @"clusterResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterType { get => this._clusterType; set => this._clusterType = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzKubernetesConfiguration_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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SourceControlConfigurationsList(SubscriptionId, ResourceGroupName, ClusterRp, ClusterType, ClusterName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterRp=ClusterRp,ClusterType=ClusterType,ClusterName=ClusterName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SourceControlConfigurationsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/cmdlets/GetAzOperation_List.cs b/src/KubernetesConfiguration/generated/cmdlets/GetAzOperation_List.cs new file mode 100644 index 000000000000..b2f77eb1b501 --- /dev/null +++ b/src/KubernetesConfiguration/generated/cmdlets/GetAzOperation_List.cs @@ -0,0 +1,309 @@ +// 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.KubernetesConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// + /// List all the available operations the KubernetesConfiguration resource provider supports. + /// + /// + /// [OpenAPI] Operations_List=>GET:"/providers/Microsoft.KubernetesConfiguration/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Description(@"List all the available operations the KubernetesConfiguration resource provider supports.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Generated] + public partial class GetAzOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration Client => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzOperation_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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + var result = await response; + WriteObject(result.Value,true); + if (result.NextLink != null) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList_Call(requestMessage, onOk, this, Pipeline); + } + } + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/cmdlets/NewAzKubernetesConfiguration_CreateExpanded.cs b/src/KubernetesConfiguration/generated/cmdlets/NewAzKubernetesConfiguration_CreateExpanded.cs new file mode 100644 index 000000000000..7c9fd98d6135 --- /dev/null +++ b/src/KubernetesConfiguration/generated/cmdlets/NewAzKubernetesConfiguration_CreateExpanded.cs @@ -0,0 +1,631 @@ +// 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.KubernetesConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// Create a new Kubernetes Source Control Configuration. + /// + /// [OpenAPI] SourceControlConfigurations_CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzKubernetesConfiguration_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration))] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Description(@"Create a new Kubernetes Source Control Configuration.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Generated] + public partial class NewAzKubernetesConfiguration_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration Client => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the kubernetes cluster. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the kubernetes cluster.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the kubernetes cluster.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private string _clusterRp; + + /// + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).", + SerializedName = @"clusterRp", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterRp { get => this._clusterRp; set => this._clusterRp = value; } + + /// Backing field for property. + private string _clusterType; + + /// + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).", + SerializedName = @"clusterResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterType { get => this._clusterType; set => this._clusterType = value; } + + /// Datetime the configuration was last applied. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Datetime the configuration was last applied.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Datetime the configuration was last applied.", + SerializedName = @"lastConfigApplied", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + public global::System.DateTime ComplianceStatusLastConfigApplied { get => SourceControlConfigurationBody.ComplianceStatusLastConfigApplied ?? default(global::System.DateTime); set => SourceControlConfigurationBody.ComplianceStatusLastConfigApplied = value; } + + /// Message from when the configuration was applied. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Message from when the configuration was applied.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Message from when the configuration was applied.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + public string ComplianceStatusMessage { get => SourceControlConfigurationBody.ComplianceStatusMessage ?? null; set => SourceControlConfigurationBody.ComplianceStatusMessage = value; } + + /// Level of the message. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Level of the message.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Level of the message.", + SerializedName = @"messageLevel", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel) })] + [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel))] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel ComplianceStatusMessageLevel { get => SourceControlConfigurationBody.ComplianceStatusMessageLevel ?? ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel)""); set => SourceControlConfigurationBody.ComplianceStatusMessageLevel = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Option to enable Helm Operator for this git configuration. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Option to enable Helm Operator for this git configuration.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Option to enable Helm Operator for this git configuration.", + SerializedName = @"enableHelmOperator", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator) })] + [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator))] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator EnableHelmOperator { get => SourceControlConfigurationBody.EnableHelmOperator ?? ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator)""); set => SourceControlConfigurationBody.EnableHelmOperator = value; } + + /// Values override for the operator Helm chart. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Values override for the operator Helm chart.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Values override for the operator Helm chart.", + SerializedName = @"chartValues", + PossibleTypes = new [] { typeof(string) })] + public string HelmOperatorPropertyChartValue { get => SourceControlConfigurationBody.HelmOperatorPropertyChartValue ?? null; set => SourceControlConfigurationBody.HelmOperatorPropertyChartValue = value; } + + /// Version of the operator Helm chart. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Version of the operator Helm chart.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Version of the operator Helm chart.", + SerializedName = @"chartVersion", + PossibleTypes = new [] { typeof(string) })] + public string HelmOperatorPropertyChartVersion { get => SourceControlConfigurationBody.HelmOperatorPropertyChartVersion ?? null; set => SourceControlConfigurationBody.HelmOperatorPropertyChartVersion = value; } + + /// 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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Source Control Configuration. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Source Control Configuration.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Source Control Configuration.", + SerializedName = @"sourceControlConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SourceControlConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Instance name of the operator - identifying the specific configuration. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Instance name of the operator - identifying the specific configuration.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Instance name of the operator - identifying the specific configuration.", + SerializedName = @"operatorInstanceName", + PossibleTypes = new [] { typeof(string) })] + public string OperatorInstanceName { get => SourceControlConfigurationBody.OperatorInstanceName ?? null; set => SourceControlConfigurationBody.OperatorInstanceName = value; } + + /// + /// The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period + /// only. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The namespace to which this operator is installed to. Maximum of 253 lower case alphanumeric characters, hyphen and period only.", + SerializedName = @"operatorNamespace", + PossibleTypes = new [] { typeof(string) })] + public string OperatorNamespace { get => SourceControlConfigurationBody.OperatorNamespace ?? null; set => SourceControlConfigurationBody.OperatorNamespace = value; } + + /// Any Parameters for the Operator instance in string format. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Any Parameters for the Operator instance in string format.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Any Parameters for the Operator instance in string format.", + SerializedName = @"operatorParams", + PossibleTypes = new [] { typeof(string) })] + public string OperatorParam { get => SourceControlConfigurationBody.OperatorParam ?? null; set => SourceControlConfigurationBody.OperatorParam = value; } + + /// Scope at which the operator will be installed. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Scope at which the operator will be installed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Scope at which the operator will be installed.", + SerializedName = @"operatorScope", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope) })] + [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope))] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope OperatorScope { get => SourceControlConfigurationBody.OperatorScope ?? ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope)""); set => SourceControlConfigurationBody.OperatorScope = value; } + + /// Type of the operator + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Type of the operator")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of the operator", + SerializedName = @"operatorType", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType) })] + [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType))] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType OperatorType { get => SourceControlConfigurationBody.OperatorType ?? ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType)""); set => SourceControlConfigurationBody.OperatorType = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Url of the SourceControl Repository. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Url of the SourceControl Repository.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Url of the SourceControl Repository.", + SerializedName = @"repositoryUrl", + PossibleTypes = new [] { typeof(string) })] + public string RepositoryUrl { get => SourceControlConfigurationBody.RepositoryUrl ?? null; set => SourceControlConfigurationBody.RepositoryUrl = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration _sourceControlConfigurationBody= new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.SourceControlConfiguration(); + + /// The SourceControl Configuration object. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration SourceControlConfigurationBody { get => this._sourceControlConfigurationBody; set => this._sourceControlConfigurationBody = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// 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 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 from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzKubernetesConfiguration_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SourceControlConfigurationsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SourceControlConfigurationsCreateOrUpdate(SubscriptionId, ResourceGroupName, ClusterRp, ClusterType, ClusterName, Name, SourceControlConfigurationBody, onOk, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterRp=ClusterRp,ClusterType=ClusterType,ClusterName=ClusterName,Name=Name,body=SourceControlConfigurationBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// 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 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.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration + WriteObject((await response)); + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName, Name=Name, body=SourceControlConfigurationBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName, Name=Name, body=SourceControlConfigurationBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/cmdlets/RemoveAzKubernetesConfiguration_Delete.cs b/src/KubernetesConfiguration/generated/cmdlets/RemoveAzKubernetesConfiguration_Delete.cs new file mode 100644 index 000000000000..b6a89e13a999 --- /dev/null +++ b/src/KubernetesConfiguration/generated/cmdlets/RemoveAzKubernetesConfiguration_Delete.cs @@ -0,0 +1,561 @@ +// 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.KubernetesConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// + /// This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source + /// repo. + /// + /// + /// [OpenAPI] SourceControlConfigurations_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzKubernetesConfiguration_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Description(@"This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Generated] + public partial class RemoveAzKubernetesConfiguration_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration Client => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.ClientAPI; + + /// Backing field for property. + private string _clusterName; + + /// The name of the kubernetes cluster. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the kubernetes cluster.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the kubernetes cluster.", + SerializedName = @"clusterName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterName { get => this._clusterName; set => this._clusterName = value; } + + /// Backing field for property. + private string _clusterRp; + + /// + /// The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters).", + SerializedName = @"clusterRp", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterRp { get => this._clusterRp; set => this._clusterRp = value; } + + /// Backing field for property. + private string _clusterType; + + /// + /// The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S + /// clusters). + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters).", + SerializedName = @"clusterResourceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ClusterType { get => this._clusterType; set => this._clusterType = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Source Control Configuration. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Source Control Configuration.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Source Control Configuration.", + SerializedName = @"sourceControlConfigurationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SourceControlConfigurationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group.")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)")] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzKubernetesConfiguration_Delete + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Cmdlets.RemoveAzKubernetesConfiguration_Delete Clone() + { + var clone = new RemoveAzKubernetesConfiguration_Delete(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.ClusterRp = this.ClusterRp; + clone.ClusterType = this.ClusterType; + clone.ClusterName = this.ClusterName; + clone.Name = this.Name; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SourceControlConfigurationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SourceControlConfigurationsDelete(SubscriptionId, ResourceGroupName, ClusterRp, ClusterType, ClusterName, Name, onOk, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ClusterRp=ClusterRp,ClusterType=ClusterType,ClusterName=ClusterName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzKubernetesConfiguration_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ClusterRp=ClusterRp, ClusterType=ClusterType, ClusterName=ClusterName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/cmdlets/RemoveAzKubernetesConfiguration_DeleteViaIdentity.cs b/src/KubernetesConfiguration/generated/cmdlets/RemoveAzKubernetesConfiguration_DeleteViaIdentity.cs new file mode 100644 index 000000000000..0e22e78e0295 --- /dev/null +++ b/src/KubernetesConfiguration/generated/cmdlets/RemoveAzKubernetesConfiguration_DeleteViaIdentity.cs @@ -0,0 +1,498 @@ +// 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.KubernetesConfiguration.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; + + /// + /// This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source + /// repo. + /// + /// + /// [OpenAPI] SourceControlConfigurations_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzKubernetesConfiguration_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Description(@"This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Generated] + public partial class RemoveAzKubernetesConfiguration_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// when specified, runs this cmdlet as a PowerShell job + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.KubernetesConfiguration Client => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue + /// asynchronously. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Category(global::Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnNoContent will be called before the regular onNoContent has been processed, allowing customization of + /// what happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onNoContent method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzKubernetesConfiguration_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Cmdlets.RemoveAzKubernetesConfiguration_DeleteViaIdentity Clone() + { + var clone = new RemoveAzKubernetesConfiguration_DeleteViaIdentity(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Information: + { + // When an operation supports asjob, Information messages must go thru verbose. + WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.DelayBeforePolling: + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + var data = messageData(); + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); + var location = response.GetFirstHeader(@"Location"); + var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; + WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SourceControlConfigurationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); + JobRepository.Add(job); + var task = instance.ProcessRecordAsync(); + job.Monitor(task); + WriteObject(job); + } + else + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SourceControlConfigurationsDeleteViaIdentity(InputObject.Id, onOk, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterRp) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterRp"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterResourceName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ClusterName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SourceControlConfigurationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SourceControlConfigurationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SourceControlConfigurationsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ClusterRp ?? null, InputObject.ClusterResourceName ?? null, InputObject.ClusterName ?? null, InputObject.SourceControlConfigurationName ?? null, onOk, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzKubernetesConfiguration_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 204 (NoContent). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnNoContent(responseMessage, ref _returnNow); + // if overrideOnNoContent has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onNoContent - response for 204 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/AsyncCommandRuntime.cs b/src/KubernetesConfiguration/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 000000000000..629945e3daac --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,828 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/AsyncJob.cs b/src/KubernetesConfiguration/generated/runtime/AsyncJob.cs new file mode 100644 index 000000000000..57eb9a345f7b --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/AsyncOperationResponse.cs b/src/KubernetesConfiguration/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 000000000000..f2341d21343a --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 000000000000..6a6ac07f005b --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 000000000000..d79951e3df12 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 000000000000..df99a778615a --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,99 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support"; + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!IsAzure || pf.Property.Name != "Id") + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = viewParameters.Type.FullName + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 000000000000..25b87005cfb3 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 000000000000..d6f37324f0a4 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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.KubernetesConfiguration.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 000000000000..03711ce79bde --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + protected override void ProcessRecord() + { + try { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append(@" +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +"); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder); + } + } + } catch (Exception ee) { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 000000000000..c43d96b5e04a --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.0"); + // 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.KubernetesConfiguration.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: KubernetesConfiguration cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.KubernetesConfiguration.private.dll"}'"); + + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.KubernetesConfiguration.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = {previewVersion}"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule KubernetesConfiguration".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/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 000000000000..25e476617016 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine(@"$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath)" +); + sb.AppendLine($@"$TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@"$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName +"); + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 000000000000..516ef3193de4 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 000000000000..dbfb31edd6cb --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 000000000000..eae31d5eb9bd --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/CollectionExtensions.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 000000000000..62ca62b94dfa --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/BuildTime/MarkdownRenderer.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 000000000000..7267aa5b8c5e --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + if (markdownInfo.SupportsPaging) + { + foreach (var parameter in SupportsPagingParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"### {alias}{Environment.NewLine}{Environment.NewLine}"); + } + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"{relatedLink}{Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 000000000000..244dd82753ac --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 000000000000..7448569c7a05 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() => $@"{ExampleNameHeader}{ExampleInfo.Name} +{ExampleCodeHeader} +{ExampleInfo.Code} +{ExampleCodeFooter} + +{ExampleInfo.Description.ToDescriptionFormat()} + +"; + } + + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Description.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 000000000000..efc057f5414b --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 000000000000..d7eea64335ce --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,291 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public string[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + RelatedLinks = commentInfo.RelatedLinks; + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (codeEndIndex ?? 0) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + if (Variant.SupportsPaging) + { + parameterStrings = parameterStrings.Append(" [-First ]").Append(" [-IncludeTotalCount]").Append(" [-Skip ]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string description) + { + Name = name; + Code = code; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}") + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 000000000000..ba97d12232b4 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,513 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BeginOutput + { + public VariantGroup VariantGroup { get; } + + public BeginOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}')) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + return sb.ToString(); + } + } + + internal class ProcessOutput + { + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + } + + internal class EndOutput + { + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new [] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new []{"
", "\r\n", "\n"}); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => new ArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, !isFirst && includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 000000000000..ce44cc6421c9 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,499 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}To construct, see NOTES section for {complexParameterName} properties and create a hash table."; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines().Replace(complexMessage, String.Empty).Replace(complexMessage.ToPsSingleLine(), String.Empty); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[]{} : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + + private const string HelpLinkPrefix = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{variantGroup.ModuleName.ToLowerInvariant()}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => !ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)); + } + return parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))).ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/PsAttributes.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 000000000000..68397008d667 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/PsExtensions.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 000000000000..357259ec3bdb --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal static class PsExtensions + { + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/PsHelpers.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 000000000000..cac83e2cacc0 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path '{scriptFolder}' -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.StartsWith(GuidStart))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/BuildTime/StringExtensions.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 000000000000..a8daa06cd3a7 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/BuildTime/XmlExtensions.cs b/src/KubernetesConfiguration/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 000000000000..2ff0391ad823 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/CmdInfoHandler.cs b/src/KubernetesConfiguration/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 000000000000..c57f1028b5b5 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/ConversionException.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 000000000000..56f28f9a0d8c --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/IJsonConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 000000000000..84d9b8c15a33 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/BinaryConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 000000000000..29998810478c --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/BooleanConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 000000000000..54c2298304c7 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 000000000000..b14a88157d78 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 000000000000..1ca847a8f28b --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/DecimalConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 000000000000..d22871f5dfb3 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/DoubleConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 000000000000..105a542af1ec --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/EnumConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 000000000000..739b65bb6d7a --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/GuidConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 000000000000..9b72ebe50c56 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 000000000000..15439a0a44d7 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/Int16Converter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 000000000000..96604307a7ff --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/Int32Converter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 000000000000..9fac24f651f2 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/Int64Converter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 000000000000..0e788d3bb4fe --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 000000000000..896e46e6823f --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 000000000000..4e09d2cf9586 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/SingleConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 000000000000..8b6a18b967e1 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/StringConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 000000000000..57460ceea5ea --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 000000000000..893359fe14dd --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/UInt16Converter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 000000000000..f2a684f2ecb3 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/UInt32Converter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 000000000000..deae771b321a --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/UInt64Converter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 000000000000..17b69eb7e6ac --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/Instances/UriConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 000000000000..92f5bd12f843 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/JsonConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 000000000000..901aba002a95 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/JsonConverterAttribute.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 000000000000..99f2960e92ee --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/JsonConverterFactory.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 000000000000..96c999434293 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Conversions/StringLikeConverter.cs b/src/KubernetesConfiguration/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 000000000000..bfa4be446f41 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Customizations/IJsonSerializable.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 000000000000..3e618b44845e --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Customizations/JsonArray.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 000000000000..98b5308fcae1 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Customizations/JsonBoolean.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 000000000000..88892edcb1e1 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Customizations/JsonNode.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 000000000000..0353d01687c1 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Customizations/JsonNumber.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 000000000000..a90c2214cd14 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Customizations/JsonObject.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 000000000000..efd1fc4e6d99 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Customizations/JsonString.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 000000000000..db792f10436e --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Customizations/XNodeArray.cs b/src/KubernetesConfiguration/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 000000000000..6a521814cbf1 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Debugging.cs b/src/KubernetesConfiguration/generated/runtime/Debugging.cs new file mode 100644 index 000000000000..631435af7ec7 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/DictionaryExtensions.cs b/src/KubernetesConfiguration/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 000000000000..7e8a335d8edc --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + if (value is System.Collections.Hashtable nested) + { + HashTableToDictionary(nested, new System.Collections.Generic.Dictionary()); + } + else + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/EventData.cs b/src/KubernetesConfiguration/generated/runtime/EventData.cs new file mode 100644 index 000000000000..59a37afa18dc --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/EventDataExtensions.cs b/src/KubernetesConfiguration/generated/runtime/EventDataExtensions.cs new file mode 100644 index 000000000000..c3bf7411d274 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime +{ + using System; + + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/EventListener.cs b/src/KubernetesConfiguration/generated/runtime/EventListener.cs new file mode 100644 index 000000000000..5b837f4420e0 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Events.cs b/src/KubernetesConfiguration/generated/runtime/Events.cs new file mode 100644 index 000000000000..213dd4887d7e --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/EventsExtensions.cs b/src/KubernetesConfiguration/generated/runtime/EventsExtensions.cs new file mode 100644 index 000000000000..c9c61e2db722 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Extensions.cs b/src/KubernetesConfiguration/generated/runtime/Extensions.cs new file mode 100644 index 000000000000..0250fd74435f --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/Extensions.cs @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + using System.Linq; + + internal static partial class Extensions + { + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => headerName == each.Key).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/src/KubernetesConfiguration/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 000000000000..6b18d89c0d27 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/src/KubernetesConfiguration/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 000000000000..c56ce0665cc8 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Helpers/Seperator.cs b/src/KubernetesConfiguration/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 000000000000..2d998aa48bbb --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Helpers/TypeDetails.cs b/src/KubernetesConfiguration/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 000000000000..5b37b5ef70ba --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Helpers/XHelper.cs b/src/KubernetesConfiguration/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 000000000000..5e57ce195ea3 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/HttpPipeline.cs b/src/KubernetesConfiguration/generated/runtime/HttpPipeline.cs new file mode 100644 index 000000000000..058791898d57 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/HttpPipelineMocking.ps1 b/src/KubernetesConfiguration/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 000000000000..06d43f4c7985 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/IAssociativeArray.cs b/src/KubernetesConfiguration/generated/runtime/IAssociativeArray.cs new file mode 100644 index 000000000000..991ae40beba8 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + int Count { get; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/IHeaderSerializable.cs b/src/KubernetesConfiguration/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 000000000000..820163340f49 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/ISendAsync.cs b/src/KubernetesConfiguration/generated/runtime/ISendAsync.cs new file mode 100644 index 000000000000..2895b7cc605d --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/ISendAsync.cs @@ -0,0 +1,289 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/InfoAttribute.cs b/src/KubernetesConfiguration/generated/runtime/InfoAttribute.cs new file mode 100644 index 000000000000..15424d449f1e --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/InfoAttribute.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Iso/IsoDate.cs b/src/KubernetesConfiguration/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 000000000000..efc6738554c0 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/JsonType.cs b/src/KubernetesConfiguration/generated/runtime/JsonType.cs new file mode 100644 index 000000000000..140c138ce2db --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Method.cs b/src/KubernetesConfiguration/generated/runtime/Method.cs new file mode 100644 index 000000000000..0a6d60b3700a --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Models/JsonMember.cs b/src/KubernetesConfiguration/generated/runtime/Models/JsonMember.cs new file mode 100644 index 000000000000..94c88cdb1e4f --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Models/JsonModel.cs b/src/KubernetesConfiguration/generated/runtime/Models/JsonModel.cs new file mode 100644 index 000000000000..baf200cc2006 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Models/JsonModelCache.cs b/src/KubernetesConfiguration/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 000000000000..be0d9c444194 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/Collections/JsonArray.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 000000000000..24117eb63380 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/Collections/XImmutableArray.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 000000000000..1631c0b8e3a6 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/Collections/XList.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 000000000000..ef199bf569cf --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/Collections/XNodeArray.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 000000000000..cc0244909a3b --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Nodes/Collections/XSet.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 000000000000..f990d7e141f3 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/JsonBoolean.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 000000000000..f106f59e13cf --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/JsonDate.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 000000000000..6805b165d7fa --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/JsonNode.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 000000000000..46c5ee3edfac --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/JsonNumber.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 000000000000..8c8503ba5bdd --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Nodes/JsonObject.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 000000000000..17176e57fc12 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/JsonString.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 000000000000..27121ecbc472 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/XBinary.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 000000000000..8a7200c88b00 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Nodes/XNull.cs b/src/KubernetesConfiguration/generated/runtime/Nodes/XNull.cs new file mode 100644 index 000000000000..9e8728d801b5 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Parser/Exceptions/ParseException.cs b/src/KubernetesConfiguration/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 000000000000..98b1613986c0 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Parser/JsonParser.cs b/src/KubernetesConfiguration/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 000000000000..9433c0bf0d53 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Parser/JsonToken.cs b/src/KubernetesConfiguration/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 000000000000..34efbad2155f --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Parser/JsonTokenizer.cs b/src/KubernetesConfiguration/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 000000000000..b0d607bb9a5a --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Parser/Location.cs b/src/KubernetesConfiguration/generated/runtime/Parser/Location.cs new file mode 100644 index 000000000000..75bfab13f07a --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Parser/Readers/SourceReader.cs b/src/KubernetesConfiguration/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 000000000000..61029f7a317b --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Parser/TokenReader.cs b/src/KubernetesConfiguration/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 000000000000..a7ff020e270d --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/PipelineMocking.cs b/src/KubernetesConfiguration/generated/runtime/PipelineMocking.cs new file mode 100644 index 000000000000..350f6826ece7 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/PipelineMocking.cs @@ -0,0 +1,254 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result); + + internal static JsonNode SerializeContent(byte[] content) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (content.EndsWith("==")) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content) }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content) }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"))) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"))) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Response.cs b/src/KubernetesConfiguration/generated/runtime/Response.cs new file mode 100644 index 000000000000..399e3dc58457 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Serialization/JsonSerializer.cs b/src/KubernetesConfiguration/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 000000000000..236a02b29f07 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Serialization/PropertyTransformation.cs b/src/KubernetesConfiguration/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 000000000000..34e5ca82a18e --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/Serialization/SerializationOptions.cs b/src/KubernetesConfiguration/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 000000000000..b359ad712c36 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/SerializationMode.cs b/src/KubernetesConfiguration/generated/runtime/SerializationMode.cs new file mode 100644 index 000000000000..ddf85161eb18 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/SerializationMode.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeReadOnly = 1 << 1, + + IncludeAll = IncludeHeaders | IncludeReadOnly + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/TypeConverterExtensions.cs b/src/KubernetesConfiguration/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 000000000000..a064f1b1d960 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + } +} diff --git a/src/KubernetesConfiguration/generated/runtime/UndeclaredResponseException.cs b/src/KubernetesConfiguration/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 000000000000..2af9b914d5a0 --- /dev/null +++ b/src/KubernetesConfiguration/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject; + + // see if there is an error block in the body + json = json.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // we'll create one below. + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/generated/runtime/Writers/JsonWriter.cs b/src/KubernetesConfiguration/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 000000000000..d49ad050c826 --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/generated/runtime/delegates.cs b/src/KubernetesConfiguration/generated/runtime/delegates.cs new file mode 100644 index 000000000000..b505219aa6aa --- /dev/null +++ b/src/KubernetesConfiguration/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.KubernetesConfiguration.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/KubernetesConfiguration/help/Az.KubernetesConfiguration.md b/src/KubernetesConfiguration/help/Az.KubernetesConfiguration.md new file mode 100644 index 000000000000..a71994ecb344 --- /dev/null +++ b/src/KubernetesConfiguration/help/Az.KubernetesConfiguration.md @@ -0,0 +1,22 @@ +--- +Module Name: Az.KubernetesConfiguration +Module Guid: 5a3ae8d3-8682-4ae7-8ec2-d41c0383da2b +Download Help Link: https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration +Help Version: 1.0.0.0 +Locale: en-US +--- + +# Az.KubernetesConfiguration Module +## Description +Microsoft Azure PowerShell: KubernetesConfiguration cmdlets + +## Az.KubernetesConfiguration Cmdlets +### [Get-AzKubernetesConfiguration](Get-AzKubernetesConfiguration.md) +Gets details of the Source Control Configuration. + +### [New-AzKubernetesConfiguration](New-AzKubernetesConfiguration.md) +Create a new Kubernetes Source Control Configuration. + +### [Remove-AzKubernetesConfiguration](Remove-AzKubernetesConfiguration.md) +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. + diff --git a/src/KubernetesConfiguration/help/Get-AzKubernetesConfiguration.md b/src/KubernetesConfiguration/help/Get-AzKubernetesConfiguration.md new file mode 100644 index 000000000000..7718393ced45 --- /dev/null +++ b/src/KubernetesConfiguration/help/Get-AzKubernetesConfiguration.md @@ -0,0 +1,238 @@ +--- +external help file: +Module Name: Az.KubernetesConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/get-azkubernetesconfiguration +schema: 2.0.0 +--- + +# Get-AzKubernetesConfiguration + +## SYNOPSIS +Gets details of the Source Control Configuration. + +## SYNTAX + +### List (Default) +``` +Get-AzKubernetesConfiguration -ClusterName -ClusterRp -ClusterType + -ResourceGroupName [-SubscriptionId ] [-DefaultProfile ] [] +``` + +### Get +``` +Get-AzKubernetesConfiguration -ClusterName -ClusterRp -ClusterType -Name + -ResourceGroupName [-SubscriptionId ] [-DefaultProfile ] [] +``` + +### GetViaIdentity +``` +Get-AzKubernetesConfiguration -InputObject [-DefaultProfile ] + [] +``` + +## DESCRIPTION +Gets details of the Source Control Configuration. + +## EXAMPLES + +### Example 1: Get all configurations of kubernetes cluster +```powershell +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets all configurations of kubernetes cluster. + +### Example 2: Get a configuration of kubernetes cluster by name +```powershell +PS C:\> Get-AzKubernetesConfiguration -ResourceGroupName azureps-manual-test -ClusterName ps-connaks-t02 -ClusterRp Microsoft.Kubernetes -ClusterType ConnectedClusters -Name conf-t02 + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets a configuration of kubernetes cluster by name. + +### Example 3: Get a configuration of kubernetes cluster by object +```powershell +PS C:\> $kubConf = New-AzKubernetesConfiguration -Name conf-test02 -ClusterName connaks-dkc29c -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx +PS C:\> Get-AzKubernetesConfiguration -InputObject $kubConf + +Name Type +---- ---- +conf-t02 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets a configuration of kubernetes cluster by object. + +### Example 4: Get a configuration of kubernetes cluster by pipeline +```powershell +PS C:\> @{Id='/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/connectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/conf-test01'} | Get-AzKubernetesConfiguration + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command gets a configuration of kubernetes cluster by pipeline. + +## PARAMETERS + +### -ClusterName +The name of the kubernetes cluster. + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClusterRp +The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClusterType +The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +Name of the Source Control Configuration. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: SourceControlConfigurationName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Azure subscription ID. +This is a GUID-formatted string (e.g. +00000000-0000-0000-0000-000000000000) + +```yaml +Type: System.String[] +Parameter Sets: Get, List +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ClusterName ]`: The name of the kubernetes cluster. + - `[ClusterResourceName ]`: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + - `[ClusterRp ]`: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. + - `[SourceControlConfigurationName ]`: Name of the Source Control Configuration. + - `[SubscriptionId ]`: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + +## RELATED LINKS + diff --git a/src/KubernetesConfiguration/help/New-AzKubernetesConfiguration.md b/src/KubernetesConfiguration/help/New-AzKubernetesConfiguration.md new file mode 100644 index 000000000000..5212e635154d --- /dev/null +++ b/src/KubernetesConfiguration/help/New-AzKubernetesConfiguration.md @@ -0,0 +1,297 @@ +--- +external help file: +Module Name: Az.KubernetesConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/new-azkubernetesconfiguration +schema: 2.0.0 +--- + +# New-AzKubernetesConfiguration + +## SYNOPSIS +Create a new Kubernetes Source Control Configuration. + +## SYNTAX + +``` +New-AzKubernetesConfiguration -ClusterName -Name -ResourceGroupName + -RepositoryUrl [-ClusterType ] [-SubscriptionId ] [-ClusterScoped] + [-EnableHelmOperator] [-HelmOperatorChartValues ] [-HelmOperatorChartVersion ] + [-OperatorInstanceName ] [-OperatorNamespace ] [-OperatorParameters ] + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Create a new Kubernetes Source Control Configuration. + +## EXAMPLES + +### Example 1: Create a configuation for kubernetes cluster +```powershell +PS C:\> New-AzKubernetesConfiguration -Name conf-test01 -ClusterName connaks-d983yc -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations +``` + +This command creates a configuation for kubernetes cluster. + +## PARAMETERS + +### -ClusterName +The name of the kubernetes cluster. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClusterScoped +If passed set the scope of the Configuration to Cluster (default is nameSpace). + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClusterType +The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnableHelmOperator +Option to enable Helm Operator for this git configuration. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HelmOperatorChartValues +Values override for the operator Helm chart. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -HelmOperatorChartVersion +Version of the operator Helm chart. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Name of the Source Control Configuration. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: SourceControlConfigurationName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OperatorInstanceName +Instance name of the operator - identifying the specific configuration. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OperatorNamespace +The namespace to which this operator is installed to. +Maximum of 253 lower case alphanumeric characters, hyphen and period only. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OperatorParameters +Any Parameters for the Operator instance in string format. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RepositoryUrl +Url of the SourceControl Repository. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Azure subscription ID. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration + +## NOTES + +ALIASES + +## RELATED LINKS + diff --git a/src/KubernetesConfiguration/help/Remove-AzKubernetesConfiguration.md b/src/KubernetesConfiguration/help/Remove-AzKubernetesConfiguration.md new file mode 100644 index 000000000000..e66578975227 --- /dev/null +++ b/src/KubernetesConfiguration/help/Remove-AzKubernetesConfiguration.md @@ -0,0 +1,264 @@ +--- +external help file: +Module Name: Az.KubernetesConfiguration +online version: https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/remove-azkubernetesconfiguration +schema: 2.0.0 +--- + +# Remove-AzKubernetesConfiguration + +## SYNOPSIS +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. + +## SYNTAX + +### Delete (Default) +``` +Remove-AzKubernetesConfiguration -ClusterName -ClusterType -Name + -ResourceGroupName [-SubscriptionId ] [-DefaultProfile ] [-AsJob] [-NoWait] + [-PassThru] [-Confirm] [-WhatIf] [] +``` + +### DeleteViaIdentity +``` +Remove-AzKubernetesConfiguration -InputObject [-DefaultProfile ] + [-AsJob] [-NoWait] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. + +## EXAMPLES + +### Example 1: Remove a configuation of kubernetes cluster by name +```powershell +PS C:\> Remove-AzKubernetesConfiguration -ClusterName connaks-d983yc -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test01 + +``` + +This command removes a configuation of kubernetes cluster by name. + +### Example 2: Remove a configuation of kubernetes cluster by object +```powershell +PS C:\> $kubConf = Get-AzKubernetesConfiguration -ClusterName connaks-dkc29c -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test02 -ClusterRp Microsoft.Kubernetes +PS C:\> Remove-AzKubernetesConfiguration -InputObject $kubConf + +``` + +This command removes a configuation of kubernetes cluster by object. + +## PARAMETERS + +### -AsJob +Run the command as a job + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClusterName +The name of the kubernetes cluster. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ClusterType +The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +Name of the Source Control Configuration. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: SourceControlConfigurationName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoWait +Run the command asynchronously + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +The Azure subscription ID. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[ClusterName ]`: The name of the kubernetes cluster. + - `[ClusterResourceName ]`: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + - `[ClusterRp ]`: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + - `[Id ]`: Resource identity path + - `[ResourceGroupName ]`: The name of the resource group. + - `[SourceControlConfigurationName ]`: Name of the Source Control Configuration. + - `[SubscriptionId ]`: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) + +## RELATED LINKS + diff --git a/src/KubernetesConfiguration/how-to.md b/src/KubernetesConfiguration/how-to.md new file mode 100644 index 000000000000..3c87e787b036 --- /dev/null +++ b/src/KubernetesConfiguration/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.KubernetesConfiguration`. + +## Building `Az.KubernetesConfiguration` +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.KubernetesConfiguration` +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.KubernetesConfiguration` +To pack `Az.KubernetesConfiguration` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://docs.microsoft.com/en-us/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.KubernetesConfiguration`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.KubernetesConfiguration.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.KubernetesConfiguration.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.KubernetesConfiguration`. + - `-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.KubernetesConfiguration` 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/KubernetesConfiguration/internal/Az.KubernetesConfiguration.internal.psm1 b/src/KubernetesConfiguration/internal/Az.KubernetesConfiguration.internal.psm1 new file mode 100644 index 000000000000..d8aa25364321 --- /dev/null +++ b/src/KubernetesConfiguration/internal/Az.KubernetesConfiguration.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.KubernetesConfiguration.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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/KubernetesConfiguration/internal/Get-AzOperation.ps1 b/src/KubernetesConfiguration/internal/Get-AzOperation.ps1 new file mode 100644 index 000000000000..00e500ce11ed --- /dev/null +++ b/src/KubernetesConfiguration/internal/Get-AzOperation.ps1 @@ -0,0 +1,121 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +List all the available operations the KubernetesConfiguration resource provider supports. +.Description +List all the available operations the KubernetesConfiguration resource provider supports. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/get-azoperation +#> +function Get-AzOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.private\Get-AzOperation_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/KubernetesConfiguration/internal/New-AzKubernetesConfiguration.ps1 b/src/KubernetesConfiguration/internal/New-AzKubernetesConfiguration.ps1 new file mode 100644 index 000000000000..5efe418d17d5 --- /dev/null +++ b/src/KubernetesConfiguration/internal/New-AzKubernetesConfiguration.ps1 @@ -0,0 +1,239 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create a new Kubernetes Source Control Configuration. +.Description +Create a new Kubernetes Source Control Configuration. +.Example +PS C:\> New-AzKubernetesConfiguration -Name conf-test01 -ClusterName connaks-d983yc -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/new-azkubernetesconfiguration +#> +function New-AzKubernetesConfiguration { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + ${ClusterRp}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.DateTime] + # Datetime the configuration was last applied. + ${ComplianceStatusLastConfigApplied}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Message from when the configuration was applied. + ${ComplianceStatusMessage}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel] + # Level of the message. + ${ComplianceStatusMessageLevel}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator] + # Option to enable Helm Operator for this git configuration. + ${EnableHelmOperator}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Values override for the operator Helm chart. + ${HelmOperatorPropertyChartValue}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Version of the operator Helm chart. + ${HelmOperatorPropertyChartVersion}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Instance name of the operator - identifying the specific configuration. + ${OperatorInstanceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # The namespace to which this operator is installed to. + # Maximum of 253 lower case alphanumeric characters, hyphen and period only. + ${OperatorNamespace}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Any Parameters for the Operator instance in string format. + ${OperatorParam}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope] + # Scope at which the operator will be installed. + ${OperatorScope}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType] + # Type of the operator + ${OperatorType}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Url of the SourceControl Repository. + ${RepositoryUrl}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.KubernetesConfiguration.private\New-AzKubernetesConfiguration_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/KubernetesConfiguration/internal/ProxyCmdletDefinitions.ps1 b/src/KubernetesConfiguration/internal/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..7b152a6745a4 --- /dev/null +++ b/src/KubernetesConfiguration/internal/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,564 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +List all the available operations the KubernetesConfiguration resource provider supports. +.Description +List all the available operations the KubernetesConfiguration resource provider supports. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/get-azoperation +#> +function Get-AzOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.IResourceProviderOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.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.KubernetesConfiguration.private\Get-AzOperation_List'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create a new Kubernetes Source Control Configuration. +.Description +Create a new Kubernetes Source Control Configuration. +.Example +PS C:\> New-AzKubernetesConfiguration -Name conf-test01 -ClusterName connaks-d983yc -ResourceGroupName connaks-rg-w9vlnp -RepositoryUrl http://github.com/xxxx + +Name Type +---- ---- +conf-test01 Microsoft.KubernetesConfiguration/sourceControlConfigurations + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/new-azkubernetesconfiguration +#> +function New-AzKubernetesConfiguration { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20191101Preview.ISourceControlConfiguration])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + ${ClusterRp}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.DateTime] + # Datetime the configuration was last applied. + ${ComplianceStatusLastConfigApplied}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Message from when the configuration was applied. + ${ComplianceStatusMessage}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.MessageLevel] + # Level of the message. + ${ComplianceStatusMessageLevel}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.EnableHelmOperator] + # Option to enable Helm Operator for this git configuration. + ${EnableHelmOperator}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Values override for the operator Helm chart. + ${HelmOperatorPropertyChartValue}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Version of the operator Helm chart. + ${HelmOperatorPropertyChartVersion}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Instance name of the operator - identifying the specific configuration. + ${OperatorInstanceName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # The namespace to which this operator is installed to. + # Maximum of 253 lower case alphanumeric characters, hyphen and period only. + ${OperatorNamespace}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Any Parameters for the Operator instance in string format. + ${OperatorParam}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorScope] + # Scope at which the operator will be installed. + ${OperatorScope}, + + [Parameter()] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType])] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Support.OperatorType] + # Type of the operator + ${OperatorType}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Body')] + [System.String] + # Url of the SourceControl Repository. + ${RepositoryUrl}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.KubernetesConfiguration.private\New-AzKubernetesConfiguration_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Description +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Example +PS C:\> Remove-AzKubernetesConfiguration -ClusterName connaks-d983yc -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test01 + +.Example +PS C:\> $kubConf = Get-AzKubernetesConfiguration -ClusterName connaks-dkc29c -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test02 -ClusterRp Microsoft.Kubernetes +PS C:\> Remove-AzKubernetesConfiguration -InputObject $kubConf + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the kubernetes cluster. + [ClusterResourceName ]: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + [ClusterRp ]: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [SourceControlConfigurationName ]: Name of the Source Control Configuration. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/remove-azkubernetesconfiguration +#> +function Remove-AzKubernetesConfiguration { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + ${ClusterRp}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.KubernetesConfiguration.private\Remove-AzKubernetesConfiguration_Delete'; + DeleteViaIdentity = 'Az.KubernetesConfiguration.private\Remove-AzKubernetesConfiguration_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/KubernetesConfiguration/internal/Remove-AzKubernetesConfiguration.ps1 b/src/KubernetesConfiguration/internal/Remove-AzKubernetesConfiguration.ps1 new file mode 100644 index 000000000000..c345c924e5cc --- /dev/null +++ b/src/KubernetesConfiguration/internal/Remove-AzKubernetesConfiguration.ps1 @@ -0,0 +1,204 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Description +This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source repo. +.Example +PS C:\> Remove-AzKubernetesConfiguration -ClusterName connaks-d983yc -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test01 + +.Example +PS C:\> $kubConf = Get-AzKubernetesConfiguration -ClusterName connaks-dkc29c -ClusterType ConnectedClusters -ResourceGroupName connaks-rg-w9vlnp -Name conf-test02 -ClusterRp Microsoft.Kubernetes +PS C:\> Remove-AzKubernetesConfiguration -InputObject $kubConf + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [ClusterName ]: The name of the kubernetes cluster. + [ClusterResourceName ]: The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + [ClusterRp ]: The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + [Id ]: Resource identity path + [ResourceGroupName ]: The name of the resource group. + [SourceControlConfigurationName ]: Name of the Source Control Configuration. + [SubscriptionId ]: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000) +.Link +https://docs.microsoft.com/en-us/powershell/module/az.kubernetesconfiguration/remove-azkubernetesconfiguration +#> +function Remove-AzKubernetesConfiguration { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the kubernetes cluster. + ${ClusterName}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes (for OnPrem K8S clusters). + ${ClusterRp}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or connectedClusters (for OnPrem K8S clusters). + ${ClusterType}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SourceControlConfigurationName')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # Name of the Source Control Configuration. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [System.String] + # The name of the resource group. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The Azure subscription ID. + # This is a GUID-formatted string (e.g. + # 00000000-0000-0000-0000-000000000000) + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.IKubernetesConfigurationIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.KubernetesConfiguration.private\Remove-AzKubernetesConfiguration_Delete'; + DeleteViaIdentity = 'Az.KubernetesConfiguration.private\Remove-AzKubernetesConfiguration_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/KubernetesConfiguration/internal/readme.md b/src/KubernetesConfiguration/internal/readme.md new file mode 100644 index 000000000000..b13095f31d20 --- /dev/null +++ b/src/KubernetesConfiguration/internal/readme.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.KubernetesConfiguration.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.KubernetesConfiguration`. Instead, this sub-module is imported by the `..\custom\Az.KubernetesConfiguration.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.KubernetesConfiguration.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.KubernetesConfiguration`. \ No newline at end of file diff --git a/src/KubernetesConfiguration/pack-module.ps1 b/src/KubernetesConfiguration/pack-module.ps1 new file mode 100644 index 000000000000..c22fad33d87b --- /dev/null +++ b/src/KubernetesConfiguration/pack-module.ps1 @@ -0,0 +1,16 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/KubernetesConfiguration/readme.md b/src/KubernetesConfiguration/readme.md new file mode 100644 index 000000000000..a71fb264cac3 --- /dev/null +++ b/src/KubernetesConfiguration/readme.md @@ -0,0 +1,86 @@ + +# Az.KubernetesConfiguration +This directory contains the PowerShell module for the KubernetesConfiguration service. + +--- +## Status +[![Az.KubernetesConfiguration](https://img.shields.io/powershellgallery/v/Az.KubernetesConfiguration.svg?style=flat-square&label=Az.KubernetesConfiguration "Az.KubernetesConfiguration")](https://www.powershellgallery.com/packages/Az.KubernetesConfiguration/) + +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 1.7.4 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.KubernetesConfiguration`, see [how-to.md](how-to.md). + + +--- +## Generation Requirements +Use of the beta version of `autorest.powershell` generator requires the following: +- [NodeJS LTS](https://nodejs.org) (10.15.x LTS preferred) + - **Note**: It *will not work* with Node < 10.x. Using 11.x builds may cause issues as they may introduce instability or breaking changes. +> If you want an easy way to install and update Node, [NVS - Node Version Switcher](../nodejs/installing-via-nvs.md) or [NVM - Node Version Manager](../nodejs/installing-via-nvm.md) is recommended. +- [AutoRest](https://aka.ms/autorest) v3 beta
`npm install -g autorest@beta`
  +- PowerShell 6.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g pwsh`
  +- .NET Core SDK 2.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g dotnet-sdk-2.2`
  + +## Run Generation +In this directory, run AutoRest: +> `autorest` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +``` yaml +require: + - $(this-folder)/../readme.azure.noprofile.md +input-file: + - $(repo)/specification/kubernetesconfiguration/resource-manager/Microsoft.KubernetesConfiguration/preview/2019-11-01-preview/kubernetesconfiguration.json + +title: KubernetesConfiguration +module-version: 0.1.0 +subject-prefix: '' + +identity-correction-for-post: true + +directive: + - where: + variant: ^Create$|^CreateViaIdentity$|^CreateViaIdentityExpanded$|^Update$|^UpdateViaIdentity$ + remove: true + - where: + subject: SourceControlConfiguration + set: + subject: KubernetesConfiguration + - where: + parameter-name: ClusterResourceName + set: + parameter-name: ClusterType + - where: + verb: Set + subject: KubernetesConfiguration + set: + verb: Update + - where: + verb: New|Remove + subject: KubernetesConfiguration + hide: true + - where: + verb: Update + subject: KubernetesConfiguration + remove: true +``` diff --git a/src/KubernetesConfiguration/run-module.ps1 b/src/KubernetesConfiguration/run-module.ps1 new file mode 100644 index 000000000000..620c99bf9ff9 --- /dev/null +++ b/src/KubernetesConfiguration/run-module.ps1 @@ -0,0 +1,59 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.KubernetesConfiguration.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/KubernetesConfiguration/test-module.ps1 b/src/KubernetesConfiguration/test-module.ps1 new file mode 100644 index 000000000000..4a2e06741863 --- /dev/null +++ b/src/KubernetesConfiguration/test-module.ps1 @@ -0,0 +1,68 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Live, [switch]$Record, [switch]$Playback) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts:$false -Pester -Resources:$requireResourceModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) { + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.KubernetesConfiguration.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +if($Live) { + $TestMode = 'live' +} +if($Record) { + $TestMode = 'record' +} +try { + if ($TestMode -ne 'playback') { + setupEnv + } + $testFolder = Join-Path $PSScriptRoot 'test' + Invoke-Pester -Script @{ Path = $testFolder } -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") +} +Finally +{ + if ($TestMode -ne 'playback') { + cleanupEnv + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/KubernetesConfiguration/test/Az.KubernetesConfiguration-TestResults.xml b/src/KubernetesConfiguration/test/Az.KubernetesConfiguration-TestResults.xml new file mode 100644 index 000000000000..691472e021be --- /dev/null +++ b/src/KubernetesConfiguration/test/Az.KubernetesConfiguration-TestResults.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/KubernetesConfiguration/test/Get-AzKubernetesConfiguration.Recording.json b/src/KubernetesConfiguration/test/Get-AzKubernetesConfiguration.Recording.json new file mode 100644 index 000000000000..334fcc483b57 --- /dev/null +++ b/src/KubernetesConfiguration/test/Get-AzKubernetesConfiguration.Recording.json @@ -0,0 +1,166 @@ +{ + "Get-AzKubernetesConfiguration+[NoContext]+List+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations?api-version=2019-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "2" ], + "x-ms-client-request-id": [ "08589169-470a-4d4c-b085-47550ae96b2a" ], + "CommandName": [ "Get-AzKubernetesConfiguration" ], + "FullCommandName": [ "Get-AzKubernetesConfiguration_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-request-id": [ "d3d7627e-4181-4677-b3d6-b903b7acb194" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11997" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-correlation-request-id": [ "d3d7627e-4181-4677-b3d6-b903b7acb194" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031531Z:d3d7627e-4181-4677-b3d6-b903b7acb194" ], + "Date": [ "Fri, 03 Jul 2020 03:15:30 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "946" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test\",\"name\":\"kubconn-j9gr3h-test\",\"type\":\"Microsoft.KubernetesConfiguration/sourceControlConfigurations\",\"properties\":{\"operatorNamespace\":\"default\",\"provisioningState\":\"Succeeded\",\"complianceStatus\":{\"complianceState\":\"Pending\",\"lastConfigApplied\":\"0001-01-01T00:00:00\",\"message\":\"{\\\"OperatorMessage\\\":null,\\\"ClusterState\\\":null}\",\"messageLevel\":3},\"enableHelmOperator\":false,\"repositoryUrl\":\"http://github.com/xxxx\",\"operatorInstanceName\":\"\",\"operatorType\":\"Flux\",\"operatorScope\":\"namespace\",\"operatorParams\":\"--git-readonly\",\"repositoryPublicKey\":\"\",\"configKind\":0,\"createdDate\":\"2020-07-03T03:15:29.1338826+00:00\",\"lastModifiedDate\":\"2020-07-03T03:15:29.1338828+00:00\"}}],\"nextLink\":null}" + } + }, + "Get-AzKubernetesConfiguration+[NoContext]+Get+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "3" ], + "x-ms-client-request-id": [ "ed5cc1ce-84bc-4fbc-9706-a5b68883f15d" ], + "CommandName": [ "Get-AzKubernetesConfiguration" ], + "FullCommandName": [ "Get-AzKubernetesConfiguration_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-request-id": [ "a9e0771a-e8a7-458b-8fd9-c9f6c9852077" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11996" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-correlation-request-id": [ "a9e0771a-e8a7-458b-8fd9-c9f6c9852077" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031532Z:a9e0771a-e8a7-458b-8fd9-c9f6c9852077" ], + "Date": [ "Fri, 03 Jul 2020 03:15:31 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "918" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test\",\"name\":\"kubconn-j9gr3h-test\",\"type\":\"Microsoft.KubernetesConfiguration/sourceControlConfigurations\",\"properties\":{\"operatorNamespace\":\"default\",\"provisioningState\":\"Succeeded\",\"complianceStatus\":{\"complianceState\":\"Pending\",\"lastConfigApplied\":\"0001-01-01T00:00:00\",\"message\":\"{\\\"OperatorMessage\\\":null,\\\"ClusterState\\\":null}\",\"messageLevel\":3},\"enableHelmOperator\":false,\"repositoryUrl\":\"http://github.com/xxxx\",\"operatorInstanceName\":\"\",\"operatorType\":\"Flux\",\"operatorScope\":\"namespace\",\"operatorParams\":\"--git-readonly\",\"repositoryPublicKey\":\"\",\"configKind\":0,\"createdDate\":\"2020-07-03T03:15:29.1338826+00:00\",\"lastModifiedDate\":\"2020-07-03T03:15:29.1338828+00:00\"}}" + } + }, + "Get-AzKubernetesConfiguration+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "4" ], + "x-ms-client-request-id": [ "34bcbd2d-7e4e-4f29-a77f-d37091c57df7" ], + "CommandName": [ "Get-AzKubernetesConfiguration" ], + "FullCommandName": [ "Get-AzKubernetesConfiguration_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-request-id": [ "4193cbfa-a6c7-4c42-a18c-9993d7c36b9e" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11995" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-correlation-request-id": [ "4193cbfa-a6c7-4c42-a18c-9993d7c36b9e" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031533Z:4193cbfa-a6c7-4c42-a18c-9993d7c36b9e" ], + "Date": [ "Fri, 03 Jul 2020 03:15:33 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "918" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test\",\"name\":\"kubconn-j9gr3h-test\",\"type\":\"Microsoft.KubernetesConfiguration/sourceControlConfigurations\",\"properties\":{\"operatorNamespace\":\"default\",\"provisioningState\":\"Succeeded\",\"complianceStatus\":{\"complianceState\":\"Pending\",\"lastConfigApplied\":\"0001-01-01T00:00:00\",\"message\":\"{\\\"OperatorMessage\\\":null,\\\"ClusterState\\\":null}\",\"messageLevel\":3},\"enableHelmOperator\":false,\"repositoryUrl\":\"http://github.com/xxxx\",\"operatorInstanceName\":\"\",\"operatorType\":\"Flux\",\"operatorScope\":\"namespace\",\"operatorParams\":\"--git-readonly\",\"repositoryPublicKey\":\"\",\"configKind\":0,\"createdDate\":\"2020-07-03T03:15:29.1338826+00:00\",\"lastModifiedDate\":\"2020-07-03T03:15:29.1338828+00:00\"}}" + } + }, + "Get-AzKubernetesConfiguration+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "5" ], + "x-ms-client-request-id": [ "3380342f-b467-4206-a2bd-1d070e5978a4" ], + "CommandName": [ "Get-AzKubernetesConfiguration" ], + "FullCommandName": [ "Get-AzKubernetesConfiguration_GetViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-request-id": [ "56cd4783-a354-4f52-9570-dc3972a3603b" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11994" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-correlation-request-id": [ "56cd4783-a354-4f52-9570-dc3972a3603b" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031534Z:56cd4783-a354-4f52-9570-dc3972a3603b" ], + "Date": [ "Fri, 03 Jul 2020 03:15:34 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "918" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test\",\"name\":\"kubconn-j9gr3h-test\",\"type\":\"Microsoft.KubernetesConfiguration/sourceControlConfigurations\",\"properties\":{\"operatorNamespace\":\"default\",\"provisioningState\":\"Succeeded\",\"complianceStatus\":{\"complianceState\":\"Pending\",\"lastConfigApplied\":\"0001-01-01T00:00:00\",\"message\":\"{\\\"OperatorMessage\\\":null,\\\"ClusterState\\\":null}\",\"messageLevel\":3},\"enableHelmOperator\":false,\"repositoryUrl\":\"http://github.com/xxxx\",\"operatorInstanceName\":\"\",\"operatorType\":\"Flux\",\"operatorScope\":\"namespace\",\"operatorParams\":\"--git-readonly\",\"repositoryPublicKey\":\"\",\"configKind\":0,\"createdDate\":\"2020-07-03T03:15:29.1338826+00:00\",\"lastModifiedDate\":\"2020-07-03T03:15:29.1338828+00:00\"}}" + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/test/Get-AzKubernetesConfiguration.Tests.ps1 b/src/KubernetesConfiguration/test/Get-AzKubernetesConfiguration.Tests.ps1 new file mode 100644 index 000000000000..2b23e2592b3f --- /dev/null +++ b/src/KubernetesConfiguration/test/Get-AzKubernetesConfiguration.Tests.ps1 @@ -0,0 +1,30 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzKubernetesConfiguration.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-AzKubernetesConfiguration' { + It 'List' { + $kubConfList = Get-AzKubernetesConfiguration -ClusterName $env.kubernetesName00 -ResourceGroupName $env.resourceGroup -ClusterRp 'Microsoft.Kubernetes' -ClusterType 'ConnectedClusters' + $kubConfList.Count | Should -Be 1 + } + + It 'Get' { + $kubConf = Get-AzKubernetesConfiguration -Name $env.kubConf00 -ClusterName $env.kubernetesName00 -ResourceGroupName $env.resourceGroup -ClusterRp 'Microsoft.Kubernetes' -ClusterType 'ConnectedClusters' + $kubConf.Name | Should -Be $env.kubConf00 + } + + It 'GetViaIdentity' { + $kubConf = Get-AzKubernetesConfiguration -Name $env.kubConf00 -ClusterName $env.kubernetesName00 -ResourceGroupName $env.resourceGroup -ClusterRp 'Microsoft.Kubernetes' -ClusterType 'ConnectedClusters' + $kubConf = Get-AzKubernetesConfiguration -InputObject $kubConf + $kubConf.Name | Should -Be $env.kubConf00 + } +} diff --git a/src/KubernetesConfiguration/test/New-AzKubernetesConfiguration.Recording.json b/src/KubernetesConfiguration/test/New-AzKubernetesConfiguration.Recording.json new file mode 100644 index 000000000000..26e485ae5d5a --- /dev/null +++ b/src/KubernetesConfiguration/test/New-AzKubernetesConfiguration.Recording.json @@ -0,0 +1,38 @@ +{ + "New-AzKubernetesConfiguration+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test?api-version=2019-11-01-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test?api-version=2019-11-01-preview", + "Content": "{\n \"properties\": {\n \"enableHelmOperator\": \"false\",\n \"operatorScope\": \"namespace\",\n \"operatorType\": \"Flux\",\n \"repositoryUrl\": \"http://github.com/xxxx\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "168" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Location": [ "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1197" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-request-id": [ "aafa10ee-c2b0-483a-b682-a2e5c1c898f1" ], + "x-ms-correlation-request-id": [ "aafa10ee-c2b0-483a-b682-a2e5c1c898f1" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031535Z:aafa10ee-c2b0-483a-b682-a2e5c1c898f1" ], + "Date": [ "Fri, 03 Jul 2020 03:15:35 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "918" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test\",\"name\":\"kubconf-iwu1qm-test\",\"type\":\"Microsoft.KubernetesConfiguration/sourceControlConfigurations\",\"properties\":{\"operatorNamespace\":\"default\",\"provisioningState\":\"Succeeded\",\"complianceStatus\":{\"complianceState\":\"Pending\",\"lastConfigApplied\":\"0001-01-01T00:00:00\",\"message\":\"{\\\"OperatorMessage\\\":null,\\\"ClusterState\\\":null}\",\"messageLevel\":3},\"enableHelmOperator\":false,\"repositoryUrl\":\"http://github.com/xxxx\",\"operatorInstanceName\":\"\",\"operatorType\":\"Flux\",\"operatorScope\":\"namespace\",\"operatorParams\":\"--git-readonly\",\"repositoryPublicKey\":\"\",\"configKind\":0,\"createdDate\":\"2020-07-03T03:15:35.7387005+00:00\",\"lastModifiedDate\":\"2020-07-03T03:15:35.7387007+00:00\"}}" + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/test/New-AzKubernetesConfiguration.Tests.ps1 b/src/KubernetesConfiguration/test/New-AzKubernetesConfiguration.Tests.ps1 new file mode 100644 index 000000000000..3e5f0382e3d6 --- /dev/null +++ b/src/KubernetesConfiguration/test/New-AzKubernetesConfiguration.Tests.ps1 @@ -0,0 +1,19 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzKubernetesConfiguration.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzKubernetesConfiguration' { + It 'CreateExpanded' { + $kubConf = New-AzKubernetesConfiguration -Name $env.kubConf01 -ClusterName $env.kubernetesName01 -ResourceGroupName $env.resourceGroup -RepositoryUrl http://github.com/xxxx + $kubConf.ProvisioningState | Should -Be 'Succeeded' + } +} diff --git a/src/KubernetesConfiguration/test/Remove-AzKubernetesConfiguration.Recording.json b/src/KubernetesConfiguration/test/Remove-AzKubernetesConfiguration.Recording.json new file mode 100644 index 000000000000..44652b75cb66 --- /dev/null +++ b/src/KubernetesConfiguration/test/Remove-AzKubernetesConfiguration.Recording.json @@ -0,0 +1,203 @@ +{ + "Remove-AzKubernetesConfiguration+[NoContext]+Delete+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview+1": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconn-j9gr3h-test?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "7" ], + "x-ms-client-request-id": [ "d080bfd1-360a-40df-a10d-55e94647122a" ], + "CommandName": [ "Az.KubernetesConfiguration.internal\\Remove-AzKubernetesConfiguration" ], + "FullCommandName": [ "Remove-AzKubernetesConfiguration_Delete" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14999" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-request-id": [ "2b66188a-82e1-4c29-bc53-07a47f95817c" ], + "x-ms-correlation-request-id": [ "2b66188a-82e1-4c29-bc53-07a47f95817c" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031537Z:2b66188a-82e1-4c29-bc53-07a47f95817c" ], + "Date": [ "Fri, 03 Jul 2020 03:15:37 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "152" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"version\":\"1.1\",\"content\":null,\"statusCode\":200,\"reasonPhrase\":\"OK\",\"headers\":[],\"trailingHeaders\":[],\"requestMessage\":null,\"isSuccessStatusCode\":true}" + } + }, + "Remove-AzKubernetesConfiguration+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations?api-version=2019-11-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-d983yc/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "8" ], + "x-ms-client-request-id": [ "6a218616-e98a-4b26-a86b-7f1cfda0ab0f" ], + "CommandName": [ "Get-AzKubernetesConfiguration" ], + "FullCommandName": [ "Get-AzKubernetesConfiguration_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11993" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-request-id": [ "4596dd1a-5224-4f57-ba8d-ec522dc945ef" ], + "x-ms-correlation-request-id": [ "4596dd1a-5224-4f57-ba8d-ec522dc945ef" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031538Z:4596dd1a-5224-4f57-ba8d-ec522dc945ef" ], + "Date": [ "Fri, 03 Jul 2020 03:15:38 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "28" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[],\"nextLink\":null}" + } + }, + "Remove-AzKubernetesConfiguration+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test?api-version=2019-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "9" ], + "x-ms-client-request-id": [ "aae378e5-f26d-4490-9fb8-779ee46ce70b" ], + "CommandName": [ "Get-AzKubernetesConfiguration" ], + "FullCommandName": [ "Get-AzKubernetesConfiguration_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "Vary": [ "Accept-Encoding" ], + "x-ms-request-id": [ "3f7e2486-c0a7-49bd-8c6a-499f744e60e8" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11992" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-correlation-request-id": [ "3f7e2486-c0a7-49bd-8c6a-499f744e60e8" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031539Z:3f7e2486-c0a7-49bd-8c6a-499f744e60e8" ], + "Date": [ "Fri, 03 Jul 2020 03:15:39 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "918" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test\",\"name\":\"kubconf-iwu1qm-test\",\"type\":\"Microsoft.KubernetesConfiguration/sourceControlConfigurations\",\"properties\":{\"operatorNamespace\":\"default\",\"provisioningState\":\"Succeeded\",\"complianceStatus\":{\"complianceState\":\"Pending\",\"lastConfigApplied\":\"0001-01-01T00:00:00\",\"message\":\"{\\\"OperatorMessage\\\":null,\\\"ClusterState\\\":null}\",\"messageLevel\":3},\"enableHelmOperator\":false,\"repositoryUrl\":\"http://github.com/xxxx\",\"operatorInstanceName\":\"\",\"operatorType\":\"Flux\",\"operatorScope\":\"namespace\",\"operatorParams\":\"--git-readonly\",\"repositoryPublicKey\":\"\",\"configKind\":0,\"createdDate\":\"2020-07-03T03:15:35.7387005+00:00\",\"lastModifiedDate\":\"2020-07-03T03:15:35.7387007+00:00\"}}" + } + }, + "Remove-AzKubernetesConfiguration+[NoContext]+DeleteViaIdentity+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test?api-version=2019-11-01-preview+2": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/kubconf-iwu1qm-test?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "10" ], + "x-ms-client-request-id": [ "0c7c44c9-4a01-4e44-8e2c-fa2eae216369" ], + "CommandName": [ "Az.KubernetesConfiguration.internal\\Remove-AzKubernetesConfiguration" ], + "FullCommandName": [ "Remove-AzKubernetesConfiguration_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14998" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-request-id": [ "05725a7a-88a7-473e-b81b-73201f16de60" ], + "x-ms-correlation-request-id": [ "05725a7a-88a7-473e-b81b-73201f16de60" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031540Z:05725a7a-88a7-473e-b81b-73201f16de60" ], + "Date": [ "Fri, 03 Jul 2020 03:15:40 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "152" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"version\":\"1.1\",\"content\":null,\"statusCode\":200,\"reasonPhrase\":\"OK\",\"headers\":[],\"trailingHeaders\":[],\"requestMessage\":null,\"isSuccessStatusCode\":true}" + } + }, + "Remove-AzKubernetesConfiguration+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations?api-version=2019-11-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourceGroups/connaks-rg-w9vlnp/providers/Microsoft.Kubernetes/ConnectedClusters/connaks-dkc29c/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations?api-version=2019-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "11" ], + "x-ms-client-request-id": [ "757a302a-5168-462d-9878-930b11f91118" ], + "CommandName": [ "Get-AzKubernetesConfiguration" ], + "FullCommandName": [ "Get-AzKubernetesConfiguration_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11991" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "api-supported-versions": [ "2019-11-01-Preview" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "openresty/1.15.8.2" ], + "x-ms-request-id": [ "6b87de59-63ea-4284-8720-c4796e691c9e" ], + "x-ms-correlation-request-id": [ "6b87de59-63ea-4284-8720-c4796e691c9e" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200703T031541Z:6b87de59-63ea-4284-8720-c4796e691c9e" ], + "Date": [ "Fri, 03 Jul 2020 03:15:41 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "28" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\"value\":[],\"nextLink\":null}" + } + } +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/test/Remove-AzKubernetesConfiguration.Tests.ps1 b/src/KubernetesConfiguration/test/Remove-AzKubernetesConfiguration.Tests.ps1 new file mode 100644 index 000000000000..7bf6268da8a5 --- /dev/null +++ b/src/KubernetesConfiguration/test/Remove-AzKubernetesConfiguration.Tests.ps1 @@ -0,0 +1,27 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzKubernetesConfiguration.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzKubernetesConfiguration' { + It 'Delete' { + Remove-AzKubernetesConfiguration -Name $env.kubConf00 -ClusterName $env.kubernetesName00 -ResourceGroupName $env.resourceGroup -ClusterType 'ConnectedClusters' + $kubConfList = Get-AzKubernetesConfiguration -ClusterName $env.kubernetesName00 -ResourceGroupName $env.resourceGroup -ClusterRp 'Microsoft.Kubernetes' -ClusterType 'ConnectedClusters' + $kubConfList.Name | Should -Not -Contain $env.kubConf00 + } + + It 'DeleteViaIdentity' { + $kubConf = Get-AzKubernetesConfiguration -Name $env.kubConf01 -ClusterName $env.kubernetesName01 -ResourceGroupName $env.resourceGroup -ClusterRp 'Microsoft.Kubernetes' -ClusterType 'ConnectedClusters' + Remove-AzKubernetesConfiguration -InputObject $kubConf + $kubConfList = Get-AzKubernetesConfiguration -ClusterName $env.kubernetesName01 -ResourceGroupName $env.resourceGroup -ClusterRp 'Microsoft.Kubernetes' -ClusterType 'ConnectedClusters' + $kubConfList.Name | Should -Not -Contain $env.kubConf01 + } +} diff --git a/src/KubernetesConfiguration/test/env.json b/src/KubernetesConfiguration/test/env.json new file mode 100644 index 000000000000..a936878f84fd --- /dev/null +++ b/src/KubernetesConfiguration/test/env.json @@ -0,0 +1,10 @@ +{ + "location": "eastus", + "kubConf00": "kubconn-j9gr3h-test", + "resourceGroup": "connaks-rg-w9vlnp", + "Tenant": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "kubConf01": "kubconf-iwu1qm-test", + "kubernetesName01": "connaks-dkc29c", + "kubernetesName00": "connaks-d983yc", + "SubscriptionId": "9e223dbe-3399-4e19-88eb-0975f02ac87f" +} diff --git a/src/KubernetesConfiguration/test/loadEnv.ps1 b/src/KubernetesConfiguration/test/loadEnv.ps1 new file mode 100644 index 000000000000..c4ebf2e8310c --- /dev/null +++ b/src/KubernetesConfiguration/test/loadEnv.ps1 @@ -0,0 +1,28 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:SubscriptionId"=$env.SubscriptionId; "*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/src/KubernetesConfiguration/test/readme.md b/src/KubernetesConfiguration/test/readme.md new file mode 100644 index 000000000000..1969200c6a09 --- /dev/null +++ b/src/KubernetesConfiguration/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/KubernetesConfiguration/test/utils.ps1 b/src/KubernetesConfiguration/test/utils.ps1 new file mode 100644 index 000000000000..9806caa7cf1e --- /dev/null +++ b/src/KubernetesConfiguration/test/utils.ps1 @@ -0,0 +1,42 @@ +function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + Write-Host -ForegroundColor Yellow "WARNNING: Plese provide resource group with Azure Arc enabled Kubernetes." + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + $env.location = 'eastus' + + # Can't Azure Arc enabled Kubernetes via powershell(Kubernetes model not released) and New-AzDeployment(The template file Can't exported.) + # TODO: Kubernetes model be release or The template file can be export. + $env.resourceGroup = 'connaks-rg-w9vlnp' # 'kubconfig-rg-' + (RandomString -allChars $false -len 6) + # kubernetes in connaks-rg-w9vlnp + $env.kubernetesName00 = 'connaks-d983yc' + $env.kubernetesName01 = 'connaks-dkc29c' + + $env.kubConf00 = 'kubconf-' + (RandomString -allChars $false -len 6) + '-test' + $env.kubConf01 = 'kubconf-' + (RandomString -allChars $false -len 6) + '-test' + + + Write-Host -ForegroundColor Green "Start creating kubernetes connected for test..." + New-AzKubernetesConfiguration -Name $env.kubConf00 -ClusterName $env.kubernetesName00 -ResourceGroupName $env.resourceGroup -RepositoryUrl http://github.com/xxxx + Write-Host -ForegroundColor Green "Kubernetes connected created successfully." + # 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 + Remove-AzResourceGroup -Name $env.resourceGroup +} + diff --git a/src/MonitoringSolutions/Az.MonitoringSolutions.csproj b/src/MonitoringSolutions/Az.MonitoringSolutions.csproj new file mode 100644 index 000000000000..0dfa9a7586b4 --- /dev/null +++ b/src/MonitoringSolutions/Az.MonitoringSolutions.csproj @@ -0,0 +1,7 @@ + + + MonitoringSolutions + + + + \ No newline at end of file diff --git a/src/MonitoringSolutions/Az.MonitoringSolutions.format.ps1xml b/src/MonitoringSolutions/Az.MonitoringSolutions.format.ps1xml new file mode 100644 index 000000000000..f2ae5099720c --- /dev/null +++ b/src/MonitoringSolutions/Az.MonitoringSolutions.format.ps1xml @@ -0,0 +1,463 @@ + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.MonitoringSolutionsIdentity + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.MonitoringSolutionsIdentity + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ManagementAssociationName + + + ManagementConfigurationName + + + ProviderName + + + ResourceGroupName + + + ResourceName + + + ResourceType + + + SolutionName + + + SubscriptionId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ArmTemplateParameter + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ArmTemplateParameter + + + + + + + + + + + + + + + Name + + + Value + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError1 + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError1 + + + + + + + + + + + + + + + Code + + + Message + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociation + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociation + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationProperties + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationProperties + + + + + + + + + + + + ApplicationId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfiguration + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfiguration + + + + + + + + + + + + + + + + + + Location + + + Name + + + Type + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationProperties + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationProperties + + + + + + + + + + + + + + + + + + ApplicationId + + + ParentResourceType + + + ProvisioningState + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Operation + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Operation + + + + + + + + + + + + Name + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationDisplay + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationDisplay + + + + + + + + + + + + + + + + + + Operation + + + Provider + + + Resource + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Solution + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Solution + + + + + + + + + + + + + + + + + + Name + + + Type + + + Location + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatchTags + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatchTags + + + + + + + + + + + + Item + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPlan + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPlan + + + + + + + + + + + + + + + + + + + + + Name + + + Product + + + PromotionCode + + + Publisher + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionProperties + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionProperties + + + + + + + + + + + + + + + + + + + + + ContainedResource + + + ProvisioningState + + + ReferencedResource + + + WorkspaceResourceId + + + + + + + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTags + + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTags + + + + + + + + + + + + Item + + + + + + + + \ No newline at end of file diff --git a/src/MonitoringSolutions/Az.MonitoringSolutions.psd1 b/src/MonitoringSolutions/Az.MonitoringSolutions.psd1 new file mode 100644 index 000000000000..813b09c4c3f0 --- /dev/null +++ b/src/MonitoringSolutions/Az.MonitoringSolutions.psd1 @@ -0,0 +1,25 @@ +@{ + GUID = '4e0cdc62-833e-41bd-aa97-f8f042986de3' + RootModule = './Az.MonitoringSolutions.psm1' + ModuleVersion = '0.1.0' + CompatiblePSEditions = 'Core', 'Desktop' + Author = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' + Copyright = 'Microsoft Corporation. All rights reserved.' + Description = 'Microsoft Azure PowerShell: MonitoringSolutions cmdlets' + PowerShellVersion = '5.1' + DotNetFrameworkVersion = '4.7.2' + RequiredAssemblies = './bin/Az.MonitoringSolutions.private.dll' + RequiredModules = @(@{ModuleName = 'Az.Accounts'; ModuleVersion = '1.9.0'; }) + FormatsToProcess = './Az.MonitoringSolutions.format.ps1xml' + FunctionsToExport = 'Get-AzMonitorLogAnalyticsSolution', 'New-AzMonitorLogAnalyticsSolution', 'Remove-AzMonitorLogAnalyticsSolution', 'Update-AzMonitorLogAnalyticsSolution' + AliasesToExport = '*' + PrivateData = @{ + PSData = @{ + Tags = 'Azure', 'ResourceManager', 'ARM', 'PSModule', 'MonitoringSolutions' + LicenseUri = 'https://aka.ms/azps-license' + ProjectUri = 'https://github.com/Azure/azure-powershell' + ReleaseNotes = '* the first preview release' + } + } +} diff --git a/src/MonitoringSolutions/Az.MonitoringSolutions.psm1 b/src/MonitoringSolutions/Az.MonitoringSolutions.psm1 new file mode 100644 index 000000000000..76ba4ab19f36 --- /dev/null +++ b/src/MonitoringSolutions/Az.MonitoringSolutions.psm1 @@ -0,0 +1,109 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # + # Copyright Microsoft Corporation + # Licensed under the Apache License, Version 2.0 (the "License"); + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # http://www.apache.org/licenses/LICENSE-2.0 + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'1.8.1' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 1.8.1 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 1.8.1 or greater. For installation instructions, please see: https://docs.microsoft.com/en-us/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'1.8.1') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 1.8.1 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to remove '.PSSharedModules' in your home directory. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.MonitoringSolutions.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.MonitoringSolutions.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/MonitoringSolutions/ChangeLog.md b/src/MonitoringSolutions/ChangeLog.md new file mode 100644 index 000000000000..b76ecb79cf4a --- /dev/null +++ b/src/MonitoringSolutions/ChangeLog.md @@ -0,0 +1,24 @@ + +## Upcoming Release + +## Version 0.1.0 +* the first preview release + diff --git a/src/MonitoringSolutions/MSSharedLibKey.snk b/src/MonitoringSolutions/MSSharedLibKey.snk new file mode 100644 index 000000000000..695f1b38774e Binary files /dev/null and b/src/MonitoringSolutions/MSSharedLibKey.snk differ diff --git a/src/MonitoringSolutions/MonitoringSolutions.sln b/src/MonitoringSolutions/MonitoringSolutions.sln new file mode 100644 index 000000000000..d0cb10b0bb1d --- /dev/null +++ b/src/MonitoringSolutions/MonitoringSolutions.sln @@ -0,0 +1,48 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Accounts", "..\Accounts\Accounts\Accounts.csproj", "{142D7B0B-388A-4CEB-A228-7F6D423C5C2E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication", "..\Accounts\Authentication\Authentication.csproj", "{62843FE6-7575-4D88-B989-7DF7EEC0BC01}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authentication.ResourceManager", "..\Accounts\Authentication.ResourceManager\Authentication.ResourceManager.csproj", "{442C609B-A431-4A71-B289-08F0B63C83E5}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Authenticators", "..\Accounts\Authenticators\Authenticators.csproj", "{59E8F6B8-8F0E-403F-B88B-9736DBC396D9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Az.MonitoringSolutions", "Az.MonitoringSolutions.csproj", "{F4D1A7CC-82BB-45E4-ACC0-ACB39817D0D0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {142D7B0B-388A-4CEB-A228-7F6D423C5C2E}.Release|Any CPU.Build.0 = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Debug|Any CPU.Build.0 = Debug|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.ActiveCfg = Release|Any CPU + {62843FE6-7575-4D88-B989-7DF7EEC0BC01}.Release|Any CPU.Build.0 = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {442C609B-A431-4A71-B289-08F0B63C83E5}.Release|Any CPU.Build.0 = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59E8F6B8-8F0E-403F-B88B-9736DBC396D9}.Release|Any CPU.Build.0 = Release|Any CPU + {F4D1A7CC-82BB-45E4-ACC0-ACB39817D0D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F4D1A7CC-82BB-45E4-ACC0-ACB39817D0D0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F4D1A7CC-82BB-45E4-ACC0-ACB39817D0D0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F4D1A7CC-82BB-45E4-ACC0-ACB39817D0D0}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F9B3D96E-9680-40BE-A917-02EE655D6030} + EndGlobalSection +EndGlobal diff --git a/src/MonitoringSolutions/Properties/AssemblyInfo.cs b/src/MonitoringSolutions/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..9fe04d8a3512 --- /dev/null +++ b/src/MonitoringSolutions/Properties/AssemblyInfo.cs @@ -0,0 +1,28 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Microsoft Azure Powershell - MonitoringSolutions")] +[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)] +[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)] +[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)] + +[assembly: ComVisible(false)] +[assembly: CLSCompliant(false)] +[assembly: Guid("6DF92186-DAF5-4E78-83C1-3C202359FEC0")] +[assembly: AssemblyVersion("0.1.0")] +[assembly: AssemblyFileVersion("0.1.0")] \ No newline at end of file diff --git a/src/MonitoringSolutions/build-module.ps1 b/src/MonitoringSolutions/build-module.ps1 new file mode 100644 index 000000000000..078bda077754 --- /dev/null +++ b/src/MonitoringSolutions/build-module.ps1 @@ -0,0 +1,153 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $Isolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.MonitoringSolutions' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: MonitoringSolutions cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.MonitoringSolutions.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/src/MonitoringSolutions/check-dependencies.ps1 b/src/MonitoringSolutions/check-dependencies.ps1 new file mode 100644 index 000000000000..513c52ca2fb5 --- /dev/null +++ b/src/MonitoringSolutions/check-dependencies.ps1 @@ -0,0 +1,64 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [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)) { + $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 '1.8.1' +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))) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest-beta .\readme.md --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/src/MonitoringSolutions/custom/Az.MonitoringSolutions.custom.psm1 b/src/MonitoringSolutions/custom/Az.MonitoringSolutions.custom.psm1 new file mode 100644 index 000000000000..99ee74ed6359 --- /dev/null +++ b/src/MonitoringSolutions/custom/Az.MonitoringSolutions.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.MonitoringSolutions.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.MonitoringSolutions.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/MonitoringSolutions/custom/New-AzMonitorLogAnalyticsSolution.ps1 b/src/MonitoringSolutions/custom/New-AzMonitorLogAnalyticsSolution.ps1 new file mode 100644 index 000000000000..6c45d6ccea76 --- /dev/null +++ b/src/MonitoringSolutions/custom/New-AzMonitorLogAnalyticsSolution.ps1 @@ -0,0 +1,132 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a log analytics solution. +.Description +Creates a log analytics solution. +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/new-azmonitorloganalyticssolution +.LINK +[Get-AzOperationalInsightsWorkspace](https://docs.microsoft.com/en-us/powershell/module/az.operationalinsights/get-azoperationalinsightsworkspace) +#> +function New-AzMonitorLogAnalyticsSolution { + [OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] + [CmdletBinding(DefaultParameterSetName = 'CreateExpanded', PositionalBinding = $false, SupportsShouldProcess, ConfirmImpact = 'Medium')] + param( + [Parameter(Mandatory)] + [Alias('SolutionType')] + [System.String] + # Type of the solution to be created. For example "Container". + ${Type}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script = '(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Resource location. Must be the same as the log analytic workspace. + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info(PossibleTypes = ([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # The Azure resource ID for the workspace where the solution will be deployed/enabled. + ${WorkspaceResourceId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} + ) + + process { + $resourceIdentifier = [Microsoft.Azure.Management.Internal.Resources.Utilities.Models.ResourceIdentifier]::new($WorkspaceResourceId) + $workspaceName = $resourceIdentifier.ResourceName + $solutionName = "$Type($workspaceName)" + $PSBoundParameters.Add('Name', $solutionName) | Out-Null + $PSBoundParameters.Add('PlanName', $solutionName) | Out-Null + $PSBoundParameters.Add('PlanProduct', "OMSGallery/$Type") | Out-Null + $PSBoundParameters.Add('PlanPublisher', "Microsoft") | Out-Null + $PSBoundParameters.Add('PlanPromotionCode', "") | Out-Null + $PSBoundParameters.Remove('Type') | Out-Null + Az.MonitoringSolutions.internal\New-AzMonitorLogAnalyticsSolution @PSBoundParameters + } +} diff --git a/src/MonitoringSolutions/custom/readme.md b/src/MonitoringSolutions/custom/readme.md new file mode 100644 index 000000000000..3db42fe33afb --- /dev/null +++ b/src/MonitoringSolutions/custom/readme.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.MonitoringSolutions` 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.MonitoringSolutions.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.MonitoringSolutions` 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.MonitoringSolutions.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.MonitoringSolutions.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundemental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.MonitoringSolutions`. 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.MonitoringSolutions.Models.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propegated to reference documentation via [help comments](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.MonitoringSolutions`. +- `Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.MonitoringSolutions`. For more information, see [readme.md](..\internal/readme.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.ProfileAttribute` + - Used in C# and script cmdlets to define which Azure profiles the cmdlet supports. This is only supported for Azure (`--azure`) modules. \ No newline at end of file diff --git a/src/MonitoringSolutions/examples/Get-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/examples/Get-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..f14c699d4adc --- /dev/null +++ b/src/MonitoringSolutions/examples/Get-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,58 @@ +### Example 1: Get a monitor log analytics solution by name +```powershell +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets a monitor log analytics solution by name. + +### Example 2: Get a monitor log analytics solution by resource id +```powershell +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/azureps-manual-test/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-t01)"} | Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +``` + +This command gets a monitor log analytics solution by resource id. + +### Example 3: Get a monitor log analytics solution by object +```powershell + +PS C:\> $monitor = New-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' +PS C:\> Get-AzMonitorLogAnalyticsSolution -InputObject $monitor +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets a monitor log analytics solution by object. + +### Example 4: Get all monitor log analytics solutions under a resource group +```powershell +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets all monitor log analytics solutions under a resource group. + +### Example 5: Get all monitor log analytics solutions under a subscription +```powershell +PS C:\> Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets all monitor log analytics solutions under a subscription. + + diff --git a/src/MonitoringSolutions/examples/New-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/examples/New-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..9dc9bab70503 --- /dev/null +++ b/src/MonitoringSolutions/examples/New-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,33 @@ +### Example 1: Create a monitor log analytics solution for the log analytics workspace +```powershell +PS C:\> $workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName azureps-manual-test -Name monitoringworkspace-2vob7n +PS C:\> New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName azureps-manual-test -Location $workspace.Location -WorkspaceResourceId $workspace.ResourceId + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +``` + +This command creates a monitor log analytics solution for the log analytics workspace. + +Commonly used types are: + +| Type | Description | +| :-----| :----- | +| SecurityCenterFree | Azure Security Center – Free Edition | +| Security | Azure Security Center | +| Updates | Update Management | +| ContainerInsights | Azure Monitor for Containers | +| ServiceMap | Service Map | +| AzureActivity | Activity log analytics | +| ChangeTracking | Change tracking and inventory | +| VMInsights | Azure Monitor for VMs | +| SecurityInsights | Azure Sentinel | +| NetworkMonitoring | Network Performance Monitor | +| SQLVulnerabilityAssessment | SQL Vulnerability Assessment | +| SQLAdvancedThreatProtection | SQL Advanced Threat Protection | +| AntiMalware | Antimalware Assessment | +| AzureAutomation | Automation Hybrid Worker | +| LogicAppsManagement | Logic Apps Management | +| SQLDataClassification | SQL Data Discovery & Classification | + diff --git a/src/MonitoringSolutions/examples/Remove-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/examples/Remove-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..9ce4df7f55ba --- /dev/null +++ b/src/MonitoringSolutions/examples/Remove-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,25 @@ +### Example 1: Remove a monitor log analytics solution by name +```powershell +PS C:\> Remove-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' + +``` + +This command removes a monitor log analytics solution by name. + +### Example 2: Remove a monitor log analytics solution by object +```powershell +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-pevful)' +PS C:\> Remove-AzMonitorLogAnalyticsSolution -InputObject $monitor + +``` + +This command removes a monitor log analytics solution by object. + +### Example 3: Remove a monitor log analytics solution by pipeline +```powershell +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-asdehu)' | Remove-AzMonitorLogAnalyticsSolution + +``` + +This command removes a monitor log analytics solution by pipeline. + diff --git a/src/MonitoringSolutions/examples/Update-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/examples/Update-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..1c8593f10fd9 --- /dev/null +++ b/src/MonitoringSolutions/examples/Update-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,23 @@ +### Example 1: Update a monitor log analytics solution by name +```powershell +PS C:\> Update-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +``` + +This command updates a monitor log analytics solution by name. + +### Example 2: Update a monitor log analytics solution by object +```powershell +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' +PS C:\> Update-AzMonitorLogAnalyticsSolution -InputObject $monitor -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +``` + +This command updates a monitor log analytics solution by object. + diff --git a/src/MonitoringSolutions/export-surface.ps1 b/src/MonitoringSolutions/export-surface.ps1 new file mode 100644 index 000000000000..e8658c6c9cdd --- /dev/null +++ b/src/MonitoringSolutions/export-surface.ps1 @@ -0,0 +1,40 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.MonitoringSolutions.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.MonitoringSolutions' +$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/MonitoringSolutions/exports/Get-AzMonitorLogAnalyticsSolution.ps1 b/src/MonitoringSolutions/exports/Get-AzMonitorLogAnalyticsSolution.ps1 new file mode 100644 index 000000000000..c950cd6f1b3c --- /dev/null +++ b/src/MonitoringSolutions/exports/Get-AzMonitorLogAnalyticsSolution.ps1 @@ -0,0 +1,200 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Retrieves the user solution. +.Description +Retrieves the user solution. +.Example +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +.Example +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/azureps-manual-test/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-t01)"} | Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +.Example + +PS C:\> $monitor = New-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' +PS C:\> Get-AzMonitorLogAnalyticsSolution -InputObject $monitor +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +.Example +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +.Example +PS C:\> Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [ManagementAssociationName ]: User ManagementAssociation Name. + [ManagementConfigurationName ]: User Management Configuration Name. + [ProviderName ]: Provider name for the parent resource. + [ResourceGroupName ]: The name of the resource group to get. The name is case insensitive. + [ResourceName ]: Parent resource name. + [ResourceType ]: Resource type for the parent resource + [SolutionName ]: User Solution Name. + [SubscriptionId ]: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/get-azmonitorloganalyticssolution +#> +function Get-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='List1', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_Get'; + GetViaIdentity = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_GetViaIdentity'; + List = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_List'; + List1 = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/MonitoringSolutions/exports/New-AzMonitorLogAnalyticsSolution.ps1 b/src/MonitoringSolutions/exports/New-AzMonitorLogAnalyticsSolution.ps1 new file mode 100644 index 000000000000..975ed16112af --- /dev/null +++ b/src/MonitoringSolutions/exports/New-AzMonitorLogAnalyticsSolution.ps1 @@ -0,0 +1,170 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a log analytics solution. +.Description +Creates a log analytics solution. +.Example +PS C:\> $workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName azureps-manual-test -Name monitoringworkspace-2vob7n +PS C:\> New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName azureps-manual-test -Location $workspace.Location -WorkspaceResourceId $workspace.ResourceId + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/new-azmonitorloganalyticssolution +.Link + +.Link +[Get-AzOperationalInsightsWorkspace](https://docs.microsoft.com/en-us/powershell/module/az.operationalinsights/get-azoperationalinsightsworkspace) +#> +function New-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Alias('SolutionType')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Type of the solution to be created. + # For example "Container". + ${Type}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Resource location. + # Must be the same as the log analytic workspace. + ${Location}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # The Azure resource ID for the workspace where the solution will be deployed/enabled. + ${WorkspaceResourceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.MonitoringSolutions.custom\New-AzMonitorLogAnalyticsSolution'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/MonitoringSolutions/exports/ProxyCmdletDefinitions.ps1 b/src/MonitoringSolutions/exports/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..b2488425c097 --- /dev/null +++ b/src/MonitoringSolutions/exports/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,732 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Retrieves the user solution. +.Description +Retrieves the user solution. +.Example +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +.Example +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/azureps-manual-test/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-t01)"} | Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +.Example + +PS C:\> $monitor = New-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' +PS C:\> Get-AzMonitorLogAnalyticsSolution -InputObject $monitor +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +.Example +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +.Example +PS C:\> Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [ManagementAssociationName ]: User ManagementAssociation Name. + [ManagementConfigurationName ]: User Management Configuration Name. + [ProviderName ]: Provider name for the parent resource. + [ResourceGroupName ]: The name of the resource group to get. The name is case insensitive. + [ResourceName ]: Parent resource name. + [ResourceType ]: Resource type for the parent resource + [SolutionName ]: User Solution Name. + [SubscriptionId ]: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/get-azmonitorloganalyticssolution +#> +function Get-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='List1', PositionalBinding=$false)] +param( + [Parameter(ParameterSetName='Get', Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(ParameterSetName='Get', Mandatory)] + [Parameter(ParameterSetName='List', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Get')] + [Parameter(ParameterSetName='List')] + [Parameter(ParameterSetName='List1')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String[]] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='GetViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Get = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_Get'; + GetViaIdentity = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_GetViaIdentity'; + List = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_List'; + List1 = 'Az.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsSolution_List1'; + } + if (('Get', 'List', 'List1') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes the solution in the subscription. +.Description +Deletes the solution in the subscription. +.Example +PS C:\> Remove-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' + +.Example +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-pevful)' +PS C:\> Remove-AzMonitorLogAnalyticsSolution -InputObject $monitor + +.Example +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-asdehu)' | Remove-AzMonitorLogAnalyticsSolution + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [ManagementAssociationName ]: User ManagementAssociation Name. + [ManagementConfigurationName ]: User Management Configuration Name. + [ProviderName ]: Provider name for the parent resource. + [ResourceGroupName ]: The name of the resource group to get. The name is case insensitive. + [ResourceName ]: Parent resource name. + [ResourceType ]: Resource type for the parent resource + [SolutionName ]: User Solution Name. + [SubscriptionId ]: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/remove-azmonitorloganalyticssolution +#> +function Remove-AzMonitorLogAnalyticsSolution { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.MonitoringSolutions.private\Remove-AzMonitorLogAnalyticsSolution_Delete'; + DeleteViaIdentity = 'Az.MonitoringSolutions.private\Remove-AzMonitorLogAnalyticsSolution_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Update the tags of a solution. +.Description +Update the tags of a solution. +.Example +PS C:\> Update-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +.Example +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' +PS C:\> Update-AzMonitorLogAnalyticsSolution -InputObject $monitor -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [ManagementAssociationName ]: User ManagementAssociation Name. + [ManagementConfigurationName ]: User Management Configuration Name. + [ProviderName ]: Provider name for the parent resource. + [ResourceGroupName ]: The name of the resource group to get. The name is case insensitive. + [ResourceName ]: Parent resource name. + [ResourceType ]: Resource type for the parent resource + [SolutionName ]: User Solution Name. + [SubscriptionId ]: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/update-azmonitorloganalyticssolution +#> +function Update-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.MonitoringSolutions.private\Update-AzMonitorLogAnalyticsSolution_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.MonitoringSolutions.private\Update-AzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates a log analytics solution. +.Description +Creates a log analytics solution. +.Example +PS C:\> $workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName azureps-manual-test -Name monitoringworkspace-2vob7n +PS C:\> New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName azureps-manual-test -Location $workspace.Location -WorkspaceResourceId $workspace.ResourceId + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/new-azmonitorloganalyticssolution +.Link + +.Link +[Get-AzOperationalInsightsWorkspace](https://docs.microsoft.com/en-us/powershell/module/az.operationalinsights/get-azoperationalinsightsworkspace) +#> +function New-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(Mandatory)] + [Alias('SolutionType')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Type of the solution to be created. + # For example "Container". + ${Type}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Resource location. + # Must be the same as the log analytic workspace. + ${Location}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # The Azure resource ID for the workspace where the solution will be deployed/enabled. + ${WorkspaceResourceId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.MonitoringSolutions.custom\New-AzMonitorLogAnalyticsSolution'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/MonitoringSolutions/exports/Remove-AzMonitorLogAnalyticsSolution.ps1 b/src/MonitoringSolutions/exports/Remove-AzMonitorLogAnalyticsSolution.ps1 new file mode 100644 index 000000000000..ac2dd28491a0 --- /dev/null +++ b/src/MonitoringSolutions/exports/Remove-AzMonitorLogAnalyticsSolution.ps1 @@ -0,0 +1,179 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Deletes the solution in the subscription. +.Description +Deletes the solution in the subscription. +.Example +PS C:\> Remove-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' + +.Example +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-pevful)' +PS C:\> Remove-AzMonitorLogAnalyticsSolution -InputObject $monitor + +.Example +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-asdehu)' | Remove-AzMonitorLogAnalyticsSolution + + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +.Outputs +System.Boolean +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [ManagementAssociationName ]: User ManagementAssociation Name. + [ManagementConfigurationName ]: User Management Configuration Name. + [ProviderName ]: Provider name for the parent resource. + [ResourceGroupName ]: The name of the resource group to get. The name is case insensitive. + [ResourceName ]: Parent resource name. + [ResourceType ]: Resource type for the parent resource + [SolutionName ]: User Solution Name. + [SubscriptionId ]: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/remove-azmonitorloganalyticssolution +#> +function Remove-AzMonitorLogAnalyticsSolution { +[OutputType([System.Boolean])] +[CmdletBinding(DefaultParameterSetName='Delete', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='Delete', Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(ParameterSetName='Delete', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='Delete')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='DeleteViaIdentity', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Returns true when the command succeeds + ${PassThru}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + Delete = 'Az.MonitoringSolutions.private\Remove-AzMonitorLogAnalyticsSolution_Delete'; + DeleteViaIdentity = 'Az.MonitoringSolutions.private\Remove-AzMonitorLogAnalyticsSolution_DeleteViaIdentity'; + } + if (('Delete') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/MonitoringSolutions/exports/Update-AzMonitorLogAnalyticsSolution.ps1 b/src/MonitoringSolutions/exports/Update-AzMonitorLogAnalyticsSolution.ps1 new file mode 100644 index 000000000000..ad280bb2f1e7 --- /dev/null +++ b/src/MonitoringSolutions/exports/Update-AzMonitorLogAnalyticsSolution.ps1 @@ -0,0 +1,183 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Update the tags of a solution. +.Description +Update the tags of a solution. +.Example +PS C:\> Update-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +.Example +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' +PS C:\> Update-AzMonitorLogAnalyticsSolution -InputObject $monitor -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US + +.Inputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Notes +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + +INPUTOBJECT : Identity Parameter + [Id ]: Resource identity path + [ManagementAssociationName ]: User ManagementAssociation Name. + [ManagementConfigurationName ]: User Management Configuration Name. + [ProviderName ]: Provider name for the parent resource. + [ResourceGroupName ]: The name of the resource group to get. The name is case insensitive. + [ResourceName ]: Parent resource name. + [ResourceType ]: Resource type for the parent resource + [SolutionName ]: User Solution Name. + [SubscriptionId ]: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/update-azmonitorloganalyticssolution +#> +function Update-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='UpdateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(ParameterSetName='UpdateExpanded', Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='UpdateExpanded')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter(ParameterSetName='UpdateViaIdentityExpanded', Mandatory, ValueFromPipeline)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity] + # Identity Parameter + # To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + ${InputObject}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + UpdateExpanded = 'Az.MonitoringSolutions.private\Update-AzMonitorLogAnalyticsSolution_UpdateExpanded'; + UpdateViaIdentityExpanded = 'Az.MonitoringSolutions.private\Update-AzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded'; + } + if (('UpdateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/MonitoringSolutions/exports/readme.md b/src/MonitoringSolutions/exports/readme.md new file mode 100644 index 000000000000..5392850cdabb --- /dev/null +++ b/src/MonitoringSolutions/exports/readme.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.MonitoringSolutions`. No other cmdlets in this repository are directly exported. What that means is the `Az.MonitoringSolutions` module will run [Export-ModuleMember](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.MonitoringSolutions.private.dll`) and from the `..\custom\Az.MonitoringSolutions.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.MonitoringSolutions.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/MonitoringSolutions/generate-help.ps1 b/src/MonitoringSolutions/generate-help.ps1 new file mode 100644 index 000000000000..01f25007204c --- /dev/null +++ b/src/MonitoringSolutions/generate-help.ps1 @@ -0,0 +1,73 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'readme.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.MonitoringSolutions.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.MonitoringSolutions.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/MonitoringSolutions/generate-info.json b/src/MonitoringSolutions/generate-info.json new file mode 100644 index 000000000000..7a1ac9249e61 --- /dev/null +++ b/src/MonitoringSolutions/generate-info.json @@ -0,0 +1,8 @@ +{ + "autorest_core": "3.0.6282", + "autorest_powershell": "2.1.396", + "autorest": "`-- (empty)", + "node": "v10.16.0", + "autorest_remodeler": "2.1.27", + "swagger_commit": "0759640718ca4980a6cf5d18b15bc5dbb1867d4b" +} diff --git a/src/MonitoringSolutions/generated/Module.cs b/src/MonitoringSolutions/generated/Module.cs new file mode 100644 index 000000000000..9719fcac00c9 --- /dev/null +++ b/src/MonitoringSolutions/generated/Module.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline _pipelineWithProxy; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// Backing field for property. + private static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module _instance; + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module Instance => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module._instance?? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module._instance = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module()); + + /// The Name of this module + public string Name => @"Az.MonitoringSolutions"; + + /// 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.MonitoringSolutions"; + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_handler.UseProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + } + + /// Creates the module instance. + private Module() + { + /// constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + _webProxy.UseDefaultCredentials = proxyUseDefaultCredentials; + _handler.UseProxy = proxy != null; + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.PowerShell.cs new file mode 100644 index 000000000000..59be3d2e6cb1 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// Parameter to pass to ARM template + [System.ComponentModel.TypeConverter(typeof(ArmTemplateParameterTypeConverter))] + public partial class ArmTemplateParameter + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ArmTemplateParameter(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Value, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ArmTemplateParameter(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal)this).Value, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ArmTemplateParameter(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.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ArmTemplateParameter(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.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Parameter to pass to ARM template + [System.ComponentModel.TypeConverter(typeof(ArmTemplateParameterTypeConverter))] + public partial interface IArmTemplateParameter + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.TypeConverter.cs new file mode 100644 index 000000000000..4a408174bd47 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ArmTemplateParameterTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ArmTemplateParameter.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ArmTemplateParameter.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ArmTemplateParameter.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.cs new file mode 100644 index 000000000000..31a4b9d17e47 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Parameter to pass to ARM template + public partial class ArmTemplateParameter : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameterInternal + { + + /// Backing field for property. + private string _name; + + /// name of the parameter. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _value; + + /// value for the parameter. In Jtoken + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ArmTemplateParameter() + { + + } + } + /// Parameter to pass to ARM template + public partial interface IArmTemplateParameter : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// name of the parameter. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"name of the parameter.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// value for the parameter. In Jtoken + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"value for the parameter. In Jtoken ", + SerializedName = @"value", + PossibleTypes = new [] { typeof(string) })] + string Value { get; set; } + + } + /// Parameter to pass to ARM template + internal partial interface IArmTemplateParameterInternal + + { + /// name of the parameter. + string Name { get; set; } + /// value for the parameter. In Jtoken + string Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.json.cs new file mode 100644 index 000000000000..2c6ecce7f458 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ArmTemplateParameter.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Parameter to pass to ARM template + public partial class ArmTemplateParameter + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ArmTemplateParameter(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_value = If( json?.PropertyT("value"), out var __jsonValue) ? (string)__jsonValue : (string)Value;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ArmTemplateParameter(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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._value)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._value.ToString()) : null, "value" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.PowerShell.cs new file mode 100644 index 000000000000..438eb64e1cdb --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// The error body contract. + [System.ComponentModel.TypeConverter(typeof(CodeMessageErrorTypeConverter))] + public partial class CodeMessageError + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeMessageError(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError1TypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Message, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CodeMessageError(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError1TypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal)this).Message, 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.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeMessageError(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.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeMessageError(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.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The error body contract. + [System.ComponentModel.TypeConverter(typeof(CodeMessageErrorTypeConverter))] + public partial interface ICodeMessageError + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.TypeConverter.cs new file mode 100644 index 000000000000..5733a93a889c --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeMessageErrorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeMessageError.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeMessageError.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeMessageError.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.cs new file mode 100644 index 000000000000..9560aa68efd5 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.cs @@ -0,0 +1,69 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The error body contract. + public partial class CodeMessageError : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal + { + + /// The error type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)Error).Code = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 _error; + + /// The error details for a failed request. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError1()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)Error).Message = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageErrorInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError1()); set { {_error = value;} } } + + /// Creates an new instance. + public CodeMessageError() + { + + } + } + /// The error body contract. + public partial interface ICodeMessageError : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// The error type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The error type.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + + } + /// The error body contract. + internal partial interface ICodeMessageErrorInternal + + { + /// The error type. + string Code { get; set; } + /// The error details for a failed request. + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 Error { get; set; } + /// The error message. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.json.cs new file mode 100644 index 000000000000..f562e6fb4f53 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The error body contract. + public partial class CodeMessageError + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal CodeMessageError(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError1.FromJson(__jsonError) : Error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new CodeMessageError(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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.PowerShell.cs new file mode 100644 index 000000000000..ebcaa439fef3 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// The error details for a failed request. + [System.ComponentModel.TypeConverter(typeof(CodeMessageError1TypeConverter))] + public partial class CodeMessageError1 + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeMessageError1(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Message, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CodeMessageError1(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Code, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal)this).Message, 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.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeMessageError1(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.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeMessageError1(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.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The error details for a failed request. + [System.ComponentModel.TypeConverter(typeof(CodeMessageError1TypeConverter))] + public partial interface ICodeMessageError1 + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.TypeConverter.cs new file mode 100644 index 000000000000..386e2ce28eef --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeMessageError1TypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeMessageError1.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeMessageError1.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeMessageError1.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.cs new file mode 100644 index 000000000000..c1a9107e161a --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.cs @@ -0,0 +1,63 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The error details for a failed request. + public partial class CodeMessageError1 : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1Internal + { + + /// Backing field for property. + private string _code; + + /// The error type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Code { get => this._code; set => this._code = value; } + + /// Backing field for property. + private string _message; + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Message { get => this._message; set => this._message = value; } + + /// Creates an new instance. + public CodeMessageError1() + { + + } + } + /// The error details for a failed request. + public partial interface ICodeMessageError1 : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// The error type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The error type.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + + } + /// The error details for a failed request. + internal partial interface ICodeMessageError1Internal + + { + /// The error type. + string Code { get; set; } + /// The error message. + string Message { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.json.cs new file mode 100644 index 000000000000..424294e8b1ff --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/CodeMessageError1.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The error details for a failed request. + public partial class CodeMessageError1 + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal CodeMessageError1(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_code = If( json?.PropertyT("code"), out var __jsonCode) ? (string)__jsonCode : (string)Code;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)Message;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ICodeMessageError1 FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new CodeMessageError1(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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.PowerShell.cs new file mode 100644 index 000000000000..466d6a944d36 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.PowerShell.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// The container for solution. + [System.ComponentModel.TypeConverter(typeof(ManagementAssociationTypeConverter))] + public partial class ManagementAssociation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagementAssociation(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.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagementAssociation(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.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagementAssociation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).ApplicationId, 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 ManagementAssociation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal)this).ApplicationId, 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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The container for solution. + [System.ComponentModel.TypeConverter(typeof(ManagementAssociationTypeConverter))] + public partial interface IManagementAssociation + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.TypeConverter.cs new file mode 100644 index 000000000000..de0975026be1 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagementAssociationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagementAssociation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagementAssociation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagementAssociation.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.cs new file mode 100644 index 000000000000..4e26074b8bde --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.cs @@ -0,0 +1,136 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The container for solution. + public partial class ManagementAssociation : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal + { + + /// The applicationId of the appliance for this association. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string ApplicationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesInternal)Property).ApplicationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesInternal)Property).ApplicationId = value; } + + /// Backing field for property. + private string _id; + + /// Resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Backing field for property. + private string _location; + + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationProperties()); set { {_property = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties _property; + + /// + /// Properties for ManagementAssociation object supported by the OperationsManagement resource provider. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationProperties()); set => this._property = value; } + + /// Backing field for property. + private string _type; + + /// Resource type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ManagementAssociation() + { + + } + } + /// The container for solution. + public partial interface IManagementAssociation : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// The applicationId of the appliance for this association. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The applicationId of the appliance for this association.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ApplicationId { get; set; } + /// Resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource ID.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource location", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Resource type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The container for solution. + internal partial interface IManagementAssociationInternal + + { + /// The applicationId of the appliance for this association. + string ApplicationId { get; set; } + /// Resource ID. + string Id { get; set; } + /// Resource location + string Location { get; set; } + /// Resource name. + string Name { get; set; } + /// + /// Properties for ManagementAssociation object supported by the OperationsManagement resource provider. + /// + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties Property { get; set; } + /// Resource type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.json.cs new file mode 100644 index 000000000000..393f5ed2a9d1 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociation.json.cs @@ -0,0 +1,118 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The container for solution. + public partial class ManagementAssociation + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ManagementAssociation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ManagementAssociation(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationProperties.FromJson(__jsonProperties) : Property;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.PowerShell.cs new file mode 100644 index 000000000000..22bb07358add --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// ManagementAssociation properties supported by the OperationsManagement resource provider. + /// + [System.ComponentModel.TypeConverter(typeof(ManagementAssociationPropertiesTypeConverter))] + public partial class ManagementAssociationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagementAssociationProperties(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.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagementAssociationProperties(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.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagementAssociationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesInternal)this).ApplicationId, 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 ManagementAssociationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesInternal)this).ApplicationId, 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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// ManagementAssociation properties supported by the OperationsManagement resource provider. + [System.ComponentModel.TypeConverter(typeof(ManagementAssociationPropertiesTypeConverter))] + public partial interface IManagementAssociationProperties + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.TypeConverter.cs new file mode 100644 index 000000000000..5d5cf61c7a13 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagementAssociationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagementAssociationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagementAssociationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagementAssociationProperties.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.cs new file mode 100644 index 000000000000..1680649df952 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.cs @@ -0,0 +1,48 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// ManagementAssociation properties supported by the OperationsManagement resource provider. + /// + public partial class ManagementAssociationProperties : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesInternal + { + + /// Backing field for property. + private string _applicationId; + + /// The applicationId of the appliance for this association. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ApplicationId { get => this._applicationId; set => this._applicationId = value; } + + /// Creates an new instance. + public ManagementAssociationProperties() + { + + } + } + /// ManagementAssociation properties supported by the OperationsManagement resource provider. + public partial interface IManagementAssociationProperties : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// The applicationId of the appliance for this association. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The applicationId of the appliance for this association.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ApplicationId { get; set; } + + } + /// ManagementAssociation properties supported by the OperationsManagement resource provider. + internal partial interface IManagementAssociationPropertiesInternal + + { + /// The applicationId of the appliance for this association. + string ApplicationId { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.json.cs new file mode 100644 index 000000000000..519982610e2c --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationProperties.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// ManagementAssociation properties supported by the OperationsManagement resource provider. + /// + public partial class ManagementAssociationProperties + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ManagementAssociationProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ManagementAssociationProperties(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_applicationId = If( json?.PropertyT("applicationId"), out var __jsonApplicationId) ? (string)__jsonApplicationId : (string)ApplicationId;} + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._applicationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._applicationId.ToString()) : null, "applicationId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.PowerShell.cs new file mode 100644 index 000000000000..95d673b79a60 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// the list of ManagementAssociation response + [System.ComponentModel.TypeConverter(typeof(ManagementAssociationPropertiesListTypeConverter))] + public partial class ManagementAssociationPropertiesList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagementAssociationPropertiesList(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.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagementAssociationPropertiesList(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.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagementAssociationPropertiesList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagementAssociationPropertiesList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// the list of ManagementAssociation response + [System.ComponentModel.TypeConverter(typeof(ManagementAssociationPropertiesListTypeConverter))] + public partial interface IManagementAssociationPropertiesList + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.TypeConverter.cs new file mode 100644 index 000000000000..1480fc1a4f5b --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.TypeConverter.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagementAssociationPropertiesListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagementAssociationPropertiesList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagementAssociationPropertiesList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagementAssociationPropertiesList.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.cs new file mode 100644 index 000000000000..0ed0afa37b9d --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// the list of ManagementAssociation response + public partial class ManagementAssociationPropertiesList : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesListInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation[] _value; + + /// List of Management Association properties within the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ManagementAssociationPropertiesList() + { + + } + } + /// the list of ManagementAssociation response + public partial interface IManagementAssociationPropertiesList : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// List of Management Association properties within the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of Management Association properties within the subscription.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation[] Value { get; set; } + + } + /// the list of ManagementAssociation response + internal partial interface IManagementAssociationPropertiesListInternal + + { + /// List of Management Association properties within the subscription. + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.json.cs new file mode 100644 index 000000000000..5fa31f625250 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementAssociationPropertiesList.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// the list of ManagementAssociation response + public partial class ManagementAssociationPropertiesList + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociationPropertiesList FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ManagementAssociationPropertiesList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ManagementAssociationPropertiesList(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation) (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociation.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.PowerShell.cs new file mode 100644 index 000000000000..7da7a634ac48 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.PowerShell.cs @@ -0,0 +1,151 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// The container for solution. + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationTypeConverter))] + public partial class ManagementConfiguration + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagementConfiguration(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagementConfiguration(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagementConfiguration(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ApplicationId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Parameter = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[]) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Parameter, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ArmTemplateParameterTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ParentResourceType = (string) content.GetValueForProperty("ParentResourceType",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ParentResourceType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Template = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate) content.GetValueForProperty("Template",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Template, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTemplateTypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagementConfiguration(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ApplicationId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Parameter = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[]) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Parameter, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ArmTemplateParameterTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ParentResourceType = (string) content.GetValueForProperty("ParentResourceType",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ParentResourceType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Template = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate) content.GetValueForProperty("Template",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal)this).Template, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTemplateTypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The container for solution. + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationTypeConverter))] + public partial interface IManagementConfiguration + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.TypeConverter.cs new file mode 100644 index 000000000000..37c485f43816 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagementConfigurationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagementConfiguration.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagementConfiguration.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagementConfiguration.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.cs new file mode 100644 index 000000000000..fe5d2e8af1d4 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.cs @@ -0,0 +1,195 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The container for solution. + public partial class ManagementConfiguration : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal + { + + /// The applicationId of the appliance for this Management. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string ApplicationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).ApplicationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).ApplicationId = value; } + + /// Backing field for property. + private string _id; + + /// Resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Backing field for property. + private string _location; + + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Parameters to run the ARM template + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[] Parameter { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).Parameter; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).Parameter = value; } + + /// The type of the parent resource. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string ParentResourceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).ParentResourceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).ParentResourceType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties _property; + + /// + /// Properties for ManagementConfiguration object supported by the OperationsManagement resource provider. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationProperties()); set => this._property = value; } + + /// The provisioning state for the ManagementConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).ProvisioningState; } + + /// The Json object containing the ARM template to deploy + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate Template { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).Template; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)Property).Template = value; } + + /// Backing field for property. + private string _type; + + /// Resource type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ManagementConfiguration() + { + + } + } + /// The container for solution. + public partial interface IManagementConfiguration : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// The applicationId of the appliance for this Management. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The applicationId of the appliance for this Management.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ApplicationId { get; set; } + /// Resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource ID.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource location", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// Parameters to run the ARM template + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Parameters to run the ARM template", + SerializedName = @"parameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[] Parameter { get; set; } + /// The type of the parent resource. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The type of the parent resource.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + string ParentResourceType { get; set; } + /// The provisioning state for the ManagementConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state for the ManagementConfiguration.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + string ProvisioningState { get; } + /// The Json object containing the ARM template to deploy + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Json object containing the ARM template to deploy", + SerializedName = @"template", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate Template { get; set; } + /// Resource type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The container for solution. + internal partial interface IManagementConfigurationInternal + + { + /// The applicationId of the appliance for this Management. + string ApplicationId { get; set; } + /// Resource ID. + string Id { get; set; } + /// Resource location + string Location { get; set; } + /// Resource name. + string Name { get; set; } + /// Parameters to run the ARM template + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[] Parameter { get; set; } + /// The type of the parent resource. + string ParentResourceType { get; set; } + /// + /// Properties for ManagementConfiguration object supported by the OperationsManagement resource provider. + /// + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties Property { get; set; } + /// The provisioning state for the ManagementConfiguration. + string ProvisioningState { get; set; } + /// The Json object containing the ARM template to deploy + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate Template { get; set; } + /// Resource type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.json.cs new file mode 100644 index 000000000000..d1767a5f11c3 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfiguration.json.cs @@ -0,0 +1,118 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The container for solution. + public partial class ManagementConfiguration + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ManagementConfiguration(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ManagementConfiguration(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationProperties.FromJson(__jsonProperties) : Property;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.PowerShell.cs new file mode 100644 index 000000000000..3f604bf0e72d --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.PowerShell.cs @@ -0,0 +1,143 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// ManagementConfiguration properties supported by the OperationsManagement resource provider. + /// + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationPropertiesTypeConverter))] + public partial class ManagementConfigurationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagementConfigurationProperties(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagementConfigurationProperties(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagementConfigurationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ApplicationId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Parameter = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[]) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Parameter, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ArmTemplateParameterTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ParentResourceType = (string) content.GetValueForProperty("ParentResourceType",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ParentResourceType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Template = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate) content.GetValueForProperty("Template",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Template, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTemplateTypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagementConfigurationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ApplicationId = (string) content.GetValueForProperty("ApplicationId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ApplicationId, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Parameter = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[]) content.GetValueForProperty("Parameter",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Parameter, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ArmTemplateParameterTypeConverter.ConvertFrom)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ParentResourceType = (string) content.GetValueForProperty("ParentResourceType",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ParentResourceType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Template = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate) content.GetValueForProperty("Template",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal)this).Template, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTemplateTypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// ManagementConfiguration properties supported by the OperationsManagement resource provider. + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationPropertiesTypeConverter))] + public partial interface IManagementConfigurationProperties + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.TypeConverter.cs new file mode 100644 index 000000000000..2a1482e2e0bb --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagementConfigurationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagementConfigurationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagementConfigurationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagementConfigurationProperties.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.cs new file mode 100644 index 000000000000..ead439625ec7 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.cs @@ -0,0 +1,119 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// ManagementConfiguration properties supported by the OperationsManagement resource provider. + /// + public partial class ManagementConfigurationProperties : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal + { + + /// Backing field for property. + private string _applicationId; + + /// The applicationId of the appliance for this Management. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ApplicationId { get => this._applicationId; set => this._applicationId = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[] _parameter; + + /// Parameters to run the ARM template + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[] Parameter { get => this._parameter; set => this._parameter = value; } + + /// Backing field for property. + private string _parentResourceType; + + /// The type of the parent resource. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ParentResourceType { get => this._parentResourceType; set => this._parentResourceType = value; } + + /// Backing field for property. + private string _provisioningState; + + /// The provisioning state for the ManagementConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate _template; + + /// The Json object containing the ARM template to deploy + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate Template { get => (this._template = this._template ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTemplate()); set => this._template = value; } + + /// Creates an new instance. + public ManagementConfigurationProperties() + { + + } + } + /// ManagementConfiguration properties supported by the OperationsManagement resource provider. + public partial interface IManagementConfigurationProperties : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// The applicationId of the appliance for this Management. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The applicationId of the appliance for this Management.", + SerializedName = @"applicationId", + PossibleTypes = new [] { typeof(string) })] + string ApplicationId { get; set; } + /// Parameters to run the ARM template + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Parameters to run the ARM template", + SerializedName = @"parameters", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[] Parameter { get; set; } + /// The type of the parent resource. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The type of the parent resource.", + SerializedName = @"parentResourceType", + PossibleTypes = new [] { typeof(string) })] + string ParentResourceType { get; set; } + /// The provisioning state for the ManagementConfiguration. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state for the ManagementConfiguration.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + string ProvisioningState { get; } + /// The Json object containing the ARM template to deploy + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The Json object containing the ARM template to deploy", + SerializedName = @"template", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate Template { get; set; } + + } + /// ManagementConfiguration properties supported by the OperationsManagement resource provider. + internal partial interface IManagementConfigurationPropertiesInternal + + { + /// The applicationId of the appliance for this Management. + string ApplicationId { get; set; } + /// Parameters to run the ARM template + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter[] Parameter { get; set; } + /// The type of the parent resource. + string ParentResourceType { get; set; } + /// The provisioning state for the ManagementConfiguration. + string ProvisioningState { get; set; } + /// The Json object containing the ARM template to deploy + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate Template { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.json.cs new file mode 100644 index 000000000000..5d446e274f72 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationProperties.json.cs @@ -0,0 +1,122 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// ManagementConfiguration properties supported by the OperationsManagement resource provider. + /// + public partial class ManagementConfigurationProperties + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ManagementConfigurationProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ManagementConfigurationProperties(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_applicationId = If( json?.PropertyT("applicationId"), out var __jsonApplicationId) ? (string)__jsonApplicationId : (string)ApplicationId;} + {_parameter = If( json?.PropertyT("parameters"), out var __jsonParameters) ? If( __jsonParameters as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IArmTemplateParameter) (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ArmTemplateParameter.FromJson(__u) )) ))() : null : Parameter;} + {_parentResourceType = If( json?.PropertyT("parentResourceType"), out var __jsonParentResourceType) ? (string)__jsonParentResourceType : (string)ParentResourceType;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + {_template = If( json?.PropertyT("template"), out var __jsonTemplate) ? Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesTemplate.FromJson(__jsonTemplate) : Template;} + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._applicationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._applicationId.ToString()) : null, "applicationId" ,container.Add ); + if (null != this._parameter) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.XNodeArray(); + foreach( var __x in this._parameter ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("parameters",__w); + } + AddIf( null != (((object)this._parentResourceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._parentResourceType.ToString()) : null, "parentResourceType" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AddIf( null != this._template ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._template.ToJson(null,serializationMode) : null, "template" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.PowerShell.cs new file mode 100644 index 000000000000..d2a70fc724b5 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.PowerShell.cs @@ -0,0 +1,134 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// the list of ManagementConfiguration response + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationPropertiesListTypeConverter))] + public partial class ManagementConfigurationPropertiesList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagementConfigurationPropertiesList(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagementConfigurationPropertiesList(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagementConfigurationPropertiesList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagementConfigurationPropertiesList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// the list of ManagementConfiguration response + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationPropertiesListTypeConverter))] + public partial interface IManagementConfigurationPropertiesList + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.TypeConverter.cs new file mode 100644 index 000000000000..f5d7a7b49bc7 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.TypeConverter.cs @@ -0,0 +1,144 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagementConfigurationPropertiesListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagementConfigurationPropertiesList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagementConfigurationPropertiesList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagementConfigurationPropertiesList.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.cs new file mode 100644 index 000000000000..a7bcd1dd31b7 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// the list of ManagementConfiguration response + public partial class ManagementConfigurationPropertiesList : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesListInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration[] _value; + + /// List of Management Configuration properties within the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public ManagementConfigurationPropertiesList() + { + + } + } + /// the list of ManagementConfiguration response + public partial interface IManagementConfigurationPropertiesList : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// List of Management Configuration properties within the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of Management Configuration properties within the subscription.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration[] Value { get; set; } + + } + /// the list of ManagementConfiguration response + internal partial interface IManagementConfigurationPropertiesListInternal + + { + /// List of Management Configuration properties within the subscription. + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.json.cs new file mode 100644 index 000000000000..89fb10b12c34 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesList.json.cs @@ -0,0 +1,110 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// the list of ManagementConfiguration response + public partial class ManagementConfigurationPropertiesList + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesList FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ManagementConfigurationPropertiesList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ManagementConfigurationPropertiesList(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration) (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfiguration.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.PowerShell.cs new file mode 100644 index 000000000000..a74f13d4227e --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.PowerShell.cs @@ -0,0 +1,132 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// The Json object containing the ARM template to deploy + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationPropertiesTemplateTypeConverter))] + public partial class ManagementConfigurationPropertiesTemplate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagementConfigurationPropertiesTemplate(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagementConfigurationPropertiesTemplate(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.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagementConfigurationPropertiesTemplate(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 ManagementConfigurationPropertiesTemplate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + 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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The Json object containing the ARM template to deploy + [System.ComponentModel.TypeConverter(typeof(ManagementConfigurationPropertiesTemplateTypeConverter))] + public partial interface IManagementConfigurationPropertiesTemplate + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.TypeConverter.cs new file mode 100644 index 000000000000..838280a3efbd --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.TypeConverter.cs @@ -0,0 +1,145 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagementConfigurationPropertiesTemplateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagementConfigurationPropertiesTemplate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagementConfigurationPropertiesTemplate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagementConfigurationPropertiesTemplate.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.cs new file mode 100644 index 000000000000..922ea6993602 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.cs @@ -0,0 +1,31 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The Json object containing the ARM template to deploy + public partial class ManagementConfigurationPropertiesTemplate : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplateInternal + { + + /// + /// Creates an new instance. + /// + public ManagementConfigurationPropertiesTemplate() + { + + } + } + /// The Json object containing the ARM template to deploy + public partial interface IManagementConfigurationPropertiesTemplate : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + + } + /// The Json object containing the ARM template to deploy + internal partial interface IManagementConfigurationPropertiesTemplateInternal + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.json.cs new file mode 100644 index 000000000000..f965dbcff1ed --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/ManagementConfigurationPropertiesTemplate.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The Json object containing the ARM template to deploy + public partial class ManagementConfigurationPropertiesTemplate + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfigurationPropertiesTemplate FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new ManagementConfigurationPropertiesTemplate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal ManagementConfigurationPropertiesTemplate(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.PowerShell.cs new file mode 100644 index 000000000000..6876389b249b --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.PowerShell.cs @@ -0,0 +1,141 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// Supported operation of OperationsManagement resource provider. + [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); + + /// + /// 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.MonitoringSolutions.Models.Api20151101Preview.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.MonitoringSolutions.Models.Api20151101Preview.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.MonitoringSolutions.Models.Api20151101Preview.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationDisplayTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Supported operation of OperationsManagement resource provider. + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.TypeConverter.cs new file mode 100644 index 000000000000..d2694d1fc13b --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.cs new file mode 100644 index 000000000000..24b2c40a5073 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.cs @@ -0,0 +1,100 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Supported operation of OperationsManagement resource provider. + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay _display; + + /// Display metadata associated with the operation. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationDisplay()); set => this._display = value; } + + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)Display).Operation = value; } + + /// Service provider: Microsoft OperationsManagement. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)Display).Provider = value; } + + /// Resource on which the operation is performed etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationDisplay()); set { {_display = value;} } } + + /// Backing field for property. + private string _name; + + /// Operation name: {provider}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// Supported operation of OperationsManagement resource provider. + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of operation: get, read, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; set; } + /// Service provider: Microsoft OperationsManagement. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Service provider: Microsoft OperationsManagement.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; set; } + /// Resource on which the operation is performed etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource on which the operation is performed etc.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; set; } + /// Operation name: {provider}/{resource}/{operation} + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Operation name: {provider}/{resource}/{operation}", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// Supported operation of OperationsManagement resource provider. + internal partial interface IOperationInternal + + { + /// Display metadata associated with the operation. + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay Display { get; set; } + /// Type of operation: get, read, delete, etc. + string DisplayOperation { get; set; } + /// Service provider: Microsoft OperationsManagement. + string DisplayProvider { get; set; } + /// Resource on which the operation is performed etc. + string DisplayResource { get; set; } + /// Operation name: {provider}/{resource}/{operation} + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.json.cs new file mode 100644 index 000000000000..ce66ecaa6523 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Operation.json.cs @@ -0,0 +1,103 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Supported operation of OperationsManagement resource provider. + 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Models.Api20151101Preview.OperationDisplay.FromJson(__jsonDisplay) : Display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.PowerShell.cs new file mode 100644 index 000000000000..79224b16ca24 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.PowerShell.cs @@ -0,0 +1,137 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// Display metadata associated with the 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); + + /// + /// 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.MonitoringSolutions.Models.Api20151101Preview.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.MonitoringSolutions.Models.Api20151101Preview.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.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Display metadata associated with the operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.TypeConverter.cs new file mode 100644 index 000000000000..4e83bc98ace3 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.cs new file mode 100644 index 000000000000..ffa2338c9dea --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.cs @@ -0,0 +1,80 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Display metadata associated with the operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplayInternal + { + + /// Backing field for property. + private string _operation; + + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Operation { get => this._operation; set => this._operation = value; } + + /// Backing field for property. + private string _provider; + + /// Service provider: Microsoft OperationsManagement. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Provider { get => this._provider; set => this._provider = value; } + + /// Backing field for property. + private string _resource; + + /// Resource on which the operation is performed etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Resource { get => this._resource; set => this._resource = value; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// Display metadata associated with the operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// Type of operation: get, read, delete, etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Type of operation: get, read, delete, etc.", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; set; } + /// Service provider: Microsoft OperationsManagement. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Service provider: Microsoft OperationsManagement.", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; set; } + /// Resource on which the operation is performed etc. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource on which the operation is performed etc.", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; set; } + + } + /// Display metadata associated with the operation. + internal partial interface IOperationDisplayInternal + + { + /// Type of operation: get, read, delete, etc. + string Operation { get; set; } + /// Service provider: Microsoft OperationsManagement. + string Provider { get; set; } + /// Resource on which the operation is performed etc. + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.json.cs new file mode 100644 index 000000000000..63c8052aa009 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationDisplay.json.cs @@ -0,0 +1,105 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Display metadata associated with the 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)Operation;} + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)Provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)Resource;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.PowerShell.cs new file mode 100644 index 000000000000..6dc19905aa0e --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// Result of the request to list solution operations. + [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); + + /// + /// 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.MonitoringSolutions.Models.Api20151101Preview.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.MonitoringSolutions.Models.Api20151101Preview.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.MonitoringSolutions.Models.Api20151101Preview.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationTypeConverter.ConvertFrom)); + 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 + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Result of the request to list solution operations. + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial interface IOperationListResult + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.TypeConverter.cs new file mode 100644 index 000000000000..b607ecb6074a --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.cs new file mode 100644 index 000000000000..5f9664c98d9f --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.cs @@ -0,0 +1,52 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Result of the request to list solution operations. + public partial class OperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResultInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation[] _value; + + /// + /// List of solution operations supported by the OperationsManagement resource provider. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationListResult() + { + + } + } + /// Result of the request to list solution operations. + public partial interface IOperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// + /// List of solution operations supported by the OperationsManagement resource provider. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of solution operations supported by the OperationsManagement resource provider.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation[] Value { get; set; } + + } + /// Result of the request to list solution operations. + internal partial interface IOperationListResultInternal + + { + /// + /// List of solution operations supported by the OperationsManagement resource provider. + /// + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.json.cs new file mode 100644 index 000000000000..7c5b78cff7b2 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/OperationListResult.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Result of the request to list solution operations. + 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Operation.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.PowerShell.cs new file mode 100644 index 000000000000..e61ea9d35ac2 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.PowerShell.cs @@ -0,0 +1,161 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// The container for solution. + [System.ComponentModel.TypeConverter(typeof(SolutionTypeConverter))] + public partial class Solution + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Solution(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.MonitoringSolutions.Models.Api20151101Preview.ISolution DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Solution(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.MonitoringSolutions.Models.Api20151101Preview.ISolution FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Solution(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Plan = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan) content.GetValueForProperty("Plan",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Plan, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPlanTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanName = (string) content.GetValueForProperty("PlanName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanProduct = (string) content.GetValueForProperty("PlanProduct",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanProduct, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPromotionCode = (string) content.GetValueForProperty("PlanPromotionCode",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPromotionCode, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPublisher = (string) content.GetValueForProperty("PlanPublisher",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPublisher, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ContainedResource = (string[]) content.GetValueForProperty("ContainedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ContainedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ReferencedResource = (string[]) content.GetValueForProperty("ReferencedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ReferencedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).WorkspaceResourceId = (string) content.GetValueForProperty("WorkspaceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).WorkspaceResourceId, 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 Solution(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Plan = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan) content.GetValueForProperty("Plan",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Plan, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPlanTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPropertiesTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Type, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Location, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTagsTypeConverter.ConvertFrom); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanName = (string) content.GetValueForProperty("PlanName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanProduct = (string) content.GetValueForProperty("PlanProduct",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanProduct, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPromotionCode = (string) content.GetValueForProperty("PlanPromotionCode",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPromotionCode, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPublisher = (string) content.GetValueForProperty("PlanPublisher",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).PlanPublisher, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ContainedResource = (string[]) content.GetValueForProperty("ContainedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ContainedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ReferencedResource = (string[]) content.GetValueForProperty("ReferencedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).ReferencedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).WorkspaceResourceId = (string) content.GetValueForProperty("WorkspaceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal)this).WorkspaceResourceId, 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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The container for solution. + [System.ComponentModel.TypeConverter(typeof(SolutionTypeConverter))] + public partial interface ISolution + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.TypeConverter.cs new file mode 100644 index 000000000000..1b99b04f0e9f --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SolutionTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Solution.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Solution.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Solution.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.cs new file mode 100644 index 000000000000..6ef4fcc2299e --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.cs @@ -0,0 +1,324 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The container for solution. + public partial class Solution : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal + { + + /// + /// The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when + /// the solution is deleted. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string[] ContainedResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).ContainedResource; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).ContainedResource = value; } + + /// Backing field for property. + private string _id; + + /// Resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string Id { get => this._id; } + + /// Backing field for property. + private string _location; + + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.FormatTable(Index = 2)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Plan + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal.Plan { get => (this._plan = this._plan ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPlan()); set { {_plan = value;} } } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// Resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.FormatTable(Index = 0)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan _plan; + + /// + /// Plan for solution object supported by the OperationsManagement resource provider. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + internal Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan Plan { get => (this._plan = this._plan ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPlan()); set => this._plan = value; } + + /// + /// name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). + /// SolutionType part is case sensitive. For third party solution, it can be anything. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string PlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).Name = value; } + + /// + /// name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. + /// This is case sensitive + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string PlanProduct { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).Product; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).Product = value; } + + /// promotionCode, Not really used now, can you left as empty + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string PlanPromotionCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).PromotionCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).PromotionCode = value; } + + /// Publisher name. For gallery solution, it is Microsoft. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string PlanPublisher { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).Publisher; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)Plan).Publisher = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties _property; + + /// + /// Properties for solution object supported by the OperationsManagement resource provider. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + internal Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionProperties()); set => this._property = value; } + + /// The provisioning state for the solution. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).ProvisioningState; } + + /// + /// The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string[] ReferencedResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).ReferencedResource; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).ReferencedResource = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags _tag; + + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTags()); set => this._tag = value; } + + /// Backing field for property. + private string _type; + + /// Resource type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.FormatTable(Index = 1)] + public string Type { get => this._type; } + + /// + /// The azure resourceId for the workspace where the solution will be deployed/enabled. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Inlined)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.DoNotFormat] + public string WorkspaceResourceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).WorkspaceResourceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)Property).WorkspaceResourceId = value; } + + /// Creates an new instance. + public Solution() + { + + } + } + /// The container for solution. + public partial interface ISolution : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// + /// The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when + /// the solution is deleted. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when the solution is deleted.", + SerializedName = @"containedResources", + PossibleTypes = new [] { typeof(string) })] + string[] ContainedResource { get; set; } + /// Resource ID. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource ID.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// Resource location + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource location", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + /// Resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// + /// name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). + /// SolutionType part is case sensitive. For third party solution, it can be anything. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). SolutionType part is case sensitive. For third party solution, it can be anything.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string PlanName { get; set; } + /// + /// name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. + /// This is case sensitive + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. This is case sensitive", + SerializedName = @"product", + PossibleTypes = new [] { typeof(string) })] + string PlanProduct { get; set; } + /// promotionCode, Not really used now, can you left as empty + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"promotionCode, Not really used now, can you left as empty", + SerializedName = @"promotionCode", + PossibleTypes = new [] { typeof(string) })] + string PlanPromotionCode { get; set; } + /// Publisher name. For gallery solution, it is Microsoft. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher name. For gallery solution, it is Microsoft.", + SerializedName = @"publisher", + PossibleTypes = new [] { typeof(string) })] + string PlanPublisher { get; set; } + /// The provisioning state for the solution. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state for the solution.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + string ProvisioningState { get; } + /// + /// The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution.", + SerializedName = @"referencedResources", + PossibleTypes = new [] { typeof(string) })] + string[] ReferencedResource { get; set; } + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags Tag { get; set; } + /// Resource type. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"Resource type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + /// + /// The azure resourceId for the workspace where the solution will be deployed/enabled. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The azure resourceId for the workspace where the solution will be deployed/enabled.", + SerializedName = @"workspaceResourceId", + PossibleTypes = new [] { typeof(string) })] + string WorkspaceResourceId { get; set; } + + } + /// The container for solution. + internal partial interface ISolutionInternal + + { + /// + /// The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when + /// the solution is deleted. + /// + string[] ContainedResource { get; set; } + /// Resource ID. + string Id { get; set; } + /// Resource location + string Location { get; set; } + /// Resource name. + string Name { get; set; } + /// + /// Plan for solution object supported by the OperationsManagement resource provider. + /// + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan Plan { get; set; } + /// + /// name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). + /// SolutionType part is case sensitive. For third party solution, it can be anything. + /// + string PlanName { get; set; } + /// + /// name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. + /// This is case sensitive + /// + string PlanProduct { get; set; } + /// promotionCode, Not really used now, can you left as empty + string PlanPromotionCode { get; set; } + /// Publisher name. For gallery solution, it is Microsoft. + string PlanPublisher { get; set; } + /// + /// Properties for solution object supported by the OperationsManagement resource provider. + /// + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties Property { get; set; } + /// The provisioning state for the solution. + string ProvisioningState { get; set; } + /// + /// The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. + /// + string[] ReferencedResource { get; set; } + /// Resource tags + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags Tag { get; set; } + /// Resource type. + string Type { get; set; } + /// + /// The azure resourceId for the workspace where the solution will be deployed/enabled. + /// + string WorkspaceResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.json.cs new file mode 100644 index 000000000000..609e283d4ea2 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/Solution.json.cs @@ -0,0 +1,122 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The container for solution. + public partial class Solution + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new Solution(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal Solution(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_plan = If( json?.PropertyT("plan"), out var __jsonPlan) ? Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPlan.FromJson(__jsonPlan) : Plan;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionProperties.FromJson(__jsonProperties) : Property;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)Type;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)Location;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._plan ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._plan.ToJson(null,serializationMode) : null, "plan" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.PowerShell.cs new file mode 100644 index 000000000000..36d647844ff1 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// The properties of a Solution that can be patched. + [System.ComponentModel.TypeConverter(typeof(SolutionPatchTypeConverter))] + public partial class SolutionPatch + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SolutionPatch(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SolutionPatch(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SolutionPatch(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatchTagsTypeConverter.ConvertFrom); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SolutionPatch(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatchTagsTypeConverter.ConvertFrom); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// The properties of a Solution that can be patched. + [System.ComponentModel.TypeConverter(typeof(SolutionPatchTypeConverter))] + public partial interface ISolutionPatch + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.TypeConverter.cs new file mode 100644 index 000000000000..5ac21ea6bd69 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SolutionPatchTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SolutionPatch.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SolutionPatch.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SolutionPatch.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.cs new file mode 100644 index 000000000000..7b3815041928 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The properties of a Solution that can be patched. + public partial class SolutionPatch : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags _tag; + + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatchTags()); set => this._tag = value; } + + /// Creates an new instance. + public SolutionPatch() + { + + } + } + /// The properties of a Solution that can be patched. + public partial interface ISolutionPatch : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// Resource tags + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags Tag { get; set; } + + } + /// The properties of a Solution that can be patched. + internal partial interface ISolutionPatchInternal + + { + /// Resource tags + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.json.cs new file mode 100644 index 000000000000..d86dfa86f524 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatch.json.cs @@ -0,0 +1,101 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// The properties of a Solution that can be patched. + public partial class SolutionPatch + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new SolutionPatch(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal SolutionPatch(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatchTags.FromJson(__jsonTags) : Tag;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.PowerShell.cs new file mode 100644 index 000000000000..07ad44b17a5a --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(SolutionPatchTagsTypeConverter))] + public partial class SolutionPatchTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SolutionPatchTags(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SolutionPatchTags(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SolutionPatchTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SolutionPatchTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(SolutionPatchTagsTypeConverter))] + public partial interface ISolutionPatchTags + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.TypeConverter.cs new file mode 100644 index 000000000000..8a5f9f8666c3 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SolutionPatchTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SolutionPatchTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SolutionPatchTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SolutionPatchTags.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.cs new file mode 100644 index 000000000000..f79b78581597 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Resource tags + public partial class SolutionPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTagsInternal + { + + /// Creates an new instance. + public SolutionPatchTags() + { + + } + } + /// Resource tags + public partial interface ISolutionPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray + { + + } + /// Resource tags + internal partial interface ISolutionPatchTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.dictionary.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.dictionary.cs new file mode 100644 index 000000000000..9c2be039bd1a --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + public partial class SolutionPatchTags : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatchTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.json.cs new file mode 100644 index 000000000000..3b1d40ee9cff --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPatchTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Resource tags + public partial class SolutionPatchTags + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new SolutionPatchTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + /// + internal SolutionPatchTags(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.PowerShell.cs new file mode 100644 index 000000000000..c3a3d5af3d36 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.PowerShell.cs @@ -0,0 +1,141 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// Plan for solution object supported by the OperationsManagement resource provider. + /// + [System.ComponentModel.TypeConverter(typeof(SolutionPlanTypeConverter))] + public partial class SolutionPlan + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SolutionPlan(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SolutionPlan(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SolutionPlan(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Product = (string) content.GetValueForProperty("Product",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Product, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).PromotionCode = (string) content.GetValueForProperty("PromotionCode",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).PromotionCode, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Publisher, 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 SolutionPlan(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Name, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Product = (string) content.GetValueForProperty("Product",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Product, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).PromotionCode = (string) content.GetValueForProperty("PromotionCode",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).PromotionCode, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Publisher = (string) content.GetValueForProperty("Publisher",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal)this).Publisher, 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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Plan for solution object supported by the OperationsManagement resource provider. + [System.ComponentModel.TypeConverter(typeof(SolutionPlanTypeConverter))] + public partial interface ISolutionPlan + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.TypeConverter.cs new file mode 100644 index 000000000000..900743538822 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SolutionPlanTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SolutionPlan.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SolutionPlan.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SolutionPlan.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.cs new file mode 100644 index 000000000000..e1b34b84d716 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.cs @@ -0,0 +1,117 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// Plan for solution object supported by the OperationsManagement resource provider. + /// + public partial class SolutionPlan : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlanInternal + { + + /// Backing field for property. + private string _name; + + /// + /// name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). + /// SolutionType part is case sensitive. For third party solution, it can be anything. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _product; + + /// + /// name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. + /// This is case sensitive + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Product { get => this._product; set => this._product = value; } + + /// Backing field for property. + private string _promotionCode; + + /// promotionCode, Not really used now, can you left as empty + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string PromotionCode { get => this._promotionCode; set => this._promotionCode = value; } + + /// Backing field for property. + private string _publisher; + + /// Publisher name. For gallery solution, it is Microsoft. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Publisher { get => this._publisher; set => this._publisher = value; } + + /// Creates an new instance. + public SolutionPlan() + { + + } + } + /// Plan for solution object supported by the OperationsManagement resource provider. + public partial interface ISolutionPlan : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// + /// name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). + /// SolutionType part is case sensitive. For third party solution, it can be anything. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). SolutionType part is case sensitive. For third party solution, it can be anything.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// + /// name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. + /// This is case sensitive + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. This is case sensitive", + SerializedName = @"product", + PossibleTypes = new [] { typeof(string) })] + string Product { get; set; } + /// promotionCode, Not really used now, can you left as empty + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"promotionCode, Not really used now, can you left as empty", + SerializedName = @"promotionCode", + PossibleTypes = new [] { typeof(string) })] + string PromotionCode { get; set; } + /// Publisher name. For gallery solution, it is Microsoft. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher name. For gallery solution, it is Microsoft.", + SerializedName = @"publisher", + PossibleTypes = new [] { typeof(string) })] + string Publisher { get; set; } + + } + /// Plan for solution object supported by the OperationsManagement resource provider. + internal partial interface ISolutionPlanInternal + + { + /// + /// name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). + /// SolutionType part is case sensitive. For third party solution, it can be anything. + /// + string Name { get; set; } + /// + /// name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. + /// This is case sensitive + /// + string Product { get; set; } + /// promotionCode, Not really used now, can you left as empty + string PromotionCode { get; set; } + /// Publisher name. For gallery solution, it is Microsoft. + string Publisher { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.json.cs new file mode 100644 index 000000000000..35af5894201a --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPlan.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// Plan for solution object supported by the OperationsManagement resource provider. + /// + public partial class SolutionPlan + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPlan FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new SolutionPlan(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal SolutionPlan(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} + {_product = If( json?.PropertyT("product"), out var __jsonProduct) ? (string)__jsonProduct : (string)Product;} + {_promotionCode = If( json?.PropertyT("promotionCode"), out var __jsonPromotionCode) ? (string)__jsonPromotionCode : (string)PromotionCode;} + {_publisher = If( json?.PropertyT("publisher"), out var __jsonPublisher) ? (string)__jsonPublisher : (string)Publisher;} + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._product)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._product.ToString()) : null, "product" ,container.Add ); + AddIf( null != (((object)this._promotionCode)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._promotionCode.ToString()) : null, "promotionCode" ,container.Add ); + AddIf( null != (((object)this._publisher)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._publisher.ToString()) : null, "publisher" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.PowerShell.cs new file mode 100644 index 000000000000..64094e159904 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.PowerShell.cs @@ -0,0 +1,139 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// Solution properties supported by the OperationsManagement resource provider. + [System.ComponentModel.TypeConverter(typeof(SolutionPropertiesTypeConverter))] + public partial class SolutionProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SolutionProperties(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SolutionProperties(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SolutionProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ContainedResource = (string[]) content.GetValueForProperty("ContainedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ContainedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ReferencedResource = (string[]) content.GetValueForProperty("ReferencedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ReferencedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).WorkspaceResourceId = (string) content.GetValueForProperty("WorkspaceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).WorkspaceResourceId, 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 SolutionProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ContainedResource = (string[]) content.GetValueForProperty("ContainedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ContainedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ReferencedResource = (string[]) content.GetValueForProperty("ReferencedResource",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).ReferencedResource, __y => TypeConverterExtensions.SelectToArray(__y, global::System.Convert.ToString)); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).WorkspaceResourceId = (string) content.GetValueForProperty("WorkspaceResourceId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal)this).WorkspaceResourceId, 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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Solution properties supported by the OperationsManagement resource provider. + [System.ComponentModel.TypeConverter(typeof(SolutionPropertiesTypeConverter))] + public partial interface ISolutionProperties + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.TypeConverter.cs new file mode 100644 index 000000000000..31fa9d13ee80 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SolutionPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SolutionProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SolutionProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SolutionProperties.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.cs new file mode 100644 index 000000000000..b55b321ca09a --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.cs @@ -0,0 +1,121 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Solution properties supported by the OperationsManagement resource provider. + public partial class SolutionProperties : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal + { + + /// Backing field for property. + private string[] _containedResource; + + /// + /// The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when + /// the solution is deleted. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string[] ContainedResource { get => this._containedResource; set => this._containedResource = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// The provisioning state for the solution. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string[] _referencedResource; + + /// + /// The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string[] ReferencedResource { get => this._referencedResource; set => this._referencedResource = value; } + + /// Backing field for property. + private string _workspaceResourceId; + + /// + /// The azure resourceId for the workspace where the solution will be deployed/enabled. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string WorkspaceResourceId { get => this._workspaceResourceId; set => this._workspaceResourceId = value; } + + /// Creates an new instance. + public SolutionProperties() + { + + } + } + /// Solution properties supported by the OperationsManagement resource provider. + public partial interface ISolutionProperties : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// + /// The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when + /// the solution is deleted. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when the solution is deleted.", + SerializedName = @"containedResources", + PossibleTypes = new [] { typeof(string) })] + string[] ContainedResource { get; set; } + /// The provisioning state for the solution. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = true, + Description = @"The provisioning state for the solution.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + string ProvisioningState { get; } + /// + /// The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution.", + SerializedName = @"referencedResources", + PossibleTypes = new [] { typeof(string) })] + string[] ReferencedResource { get; set; } + /// + /// The azure resourceId for the workspace where the solution will be deployed/enabled. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The azure resourceId for the workspace where the solution will be deployed/enabled.", + SerializedName = @"workspaceResourceId", + PossibleTypes = new [] { typeof(string) })] + string WorkspaceResourceId { get; set; } + + } + /// Solution properties supported by the OperationsManagement resource provider. + internal partial interface ISolutionPropertiesInternal + + { + /// + /// The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when + /// the solution is deleted. + /// + string[] ContainedResource { get; set; } + /// The provisioning state for the solution. + string ProvisioningState { get; set; } + /// + /// The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. + /// + string[] ReferencedResource { get; set; } + /// + /// The azure resourceId for the workspace where the solution will be deployed/enabled. + /// + string WorkspaceResourceId { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.json.cs new file mode 100644 index 000000000000..519d6c9554a2 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionProperties.json.cs @@ -0,0 +1,126 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Solution properties supported by the OperationsManagement resource provider. + public partial class SolutionProperties + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new SolutionProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal SolutionProperties(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_containedResource = If( json?.PropertyT("containedResources"), out var __jsonContainedResources) ? If( __jsonContainedResources as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(string) (__u is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : ContainedResource;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)ProvisioningState;} + {_referencedResource = If( json?.PropertyT("referencedResources"), out var __jsonReferencedResources) ? If( __jsonReferencedResources as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonArray, out var __q) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__q, (__p)=>(string) (__p is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString __o ? (string)(__o.ToString()) : null)) ))() : null : ReferencedResource;} + {_workspaceResourceId = If( json?.PropertyT("workspaceResourceId"), out var __jsonWorkspaceResourceId) ? (string)__jsonWorkspaceResourceId : (string)WorkspaceResourceId;} + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._containedResource) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.XNodeArray(); + foreach( var __x in this._containedResource ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("containedResources",__w); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeReadOnly)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (null != this._referencedResource) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.XNodeArray(); + foreach( var __s in this._referencedResource ) + { + AddIf(null != (((object)__s)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(__s.ToString()) : null ,__r.Add); + } + container.Add("referencedResources",__r); + } + AddIf( null != (((object)this._workspaceResourceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._workspaceResourceId.ToString()) : null, "workspaceResourceId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.PowerShell.cs new file mode 100644 index 000000000000..8d23bcda20ad --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.PowerShell.cs @@ -0,0 +1,133 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// the list of solution response + [System.ComponentModel.TypeConverter(typeof(SolutionPropertiesListTypeConverter))] + public partial class SolutionPropertiesList + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SolutionPropertiesList(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SolutionPropertiesList(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SolutionPropertiesList(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTypeConverter.ConvertFrom)); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SolutionPropertiesList(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesListInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesListInternal)this).Value, __y => TypeConverterExtensions.SelectToArray(__y, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTypeConverter.ConvertFrom)); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// the list of solution response + [System.ComponentModel.TypeConverter(typeof(SolutionPropertiesListTypeConverter))] + public partial interface ISolutionPropertiesList + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.TypeConverter.cs new file mode 100644 index 000000000000..2fbcdb195f19 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SolutionPropertiesListTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SolutionPropertiesList.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SolutionPropertiesList.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SolutionPropertiesList.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.cs new file mode 100644 index 000000000000..0177c6bfa024 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.cs @@ -0,0 +1,46 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// the list of solution response + public partial class SolutionPropertiesList : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesListInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution[] _value; + + /// List of solution properties within the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution[] Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public SolutionPropertiesList() + { + + } + } + /// the list of solution response + public partial interface ISolutionPropertiesList : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// List of solution properties within the subscription. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of solution properties within the subscription.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution) })] + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution[] Value { get; set; } + + } + /// the list of solution response + internal partial interface ISolutionPropertiesListInternal + + { + /// List of solution properties within the subscription. + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution[] Value { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.json.cs new file mode 100644 index 000000000000..8e4bad6aa10f --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionPropertiesList.json.cs @@ -0,0 +1,109 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// the list of solution response + public partial class SolutionPropertiesList + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPropertiesList FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new SolutionPropertiesList(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal SolutionPropertiesList(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonArray, out var __v) ? new global::System.Func(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution) (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Solution.FromJson(__u) )) ))() : null : Value;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (null != this._value) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.PowerShell.cs new file mode 100644 index 000000000000..4f4dfec408a3 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.PowerShell.cs @@ -0,0 +1,135 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(SolutionTagsTypeConverter))] + public partial class SolutionTags + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SolutionTags(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SolutionTags(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.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SolutionTags(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SolutionTags(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + // this type is a dictionary; copy elements from source to here. + CopyFrom(content); + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + /// Resource tags + [System.ComponentModel.TypeConverter(typeof(SolutionTagsTypeConverter))] + public partial interface ISolutionTags + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.TypeConverter.cs new file mode 100644 index 000000000000..b0d398fcb701 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.TypeConverter.cs @@ -0,0 +1,142 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SolutionTagsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SolutionTags.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SolutionTags.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SolutionTags.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/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.cs new file mode 100644 index 000000000000..5e079d0cd441 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.cs @@ -0,0 +1,30 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Resource tags + public partial class SolutionTags : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTagsInternal + { + + /// Creates an new instance. + public SolutionTags() + { + + } + } + /// Resource tags + public partial interface ISolutionTags : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray + { + + } + /// Resource tags + internal partial interface ISolutionTagsInternal + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.dictionary.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.dictionary.cs new file mode 100644 index 000000000000..ba784d4fc2d9 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.dictionary.cs @@ -0,0 +1,70 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + public partial class SolutionTags : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public string this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, string value) => __additionalProperties.Add( key, value); + + public void Clear() => __additionalProperties.Clear(); + + /// + public bool ContainsKey(global::System.String key) => __additionalProperties.ContainsKey( key); + + /// + public void CopyFrom(global::System.Collections.IDictionary source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public void CopyFrom(global::System.Management.Automation.PSObject source) + { + if (null != source) + { + foreach( var property in Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.TypeConverterExtensions.GetFilteredProperties(source, new global::System.Collections.Generic.HashSet() { } ) ) + { + if ((null != property.Key && null != property.Value)) + { + this.__additionalProperties.Add(property.Key.ToString(), global::System.Management.Automation.LanguagePrimitives.ConvertTo( property.Value)); + } + } + } + } + + /// + public bool Remove(global::System.String key) => __additionalProperties.Remove( key); + + /// + /// + public bool TryGetValue(global::System.String key, out string value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionTags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.json.cs b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.json.cs new file mode 100644 index 000000000000..1555cdf1ec96 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/Api20151101Preview/SolutionTags.json.cs @@ -0,0 +1,102 @@ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Resource tags + public partial class SolutionTags + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new SolutionTags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + /// + internal SolutionTags(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet exclusions = null) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray)this).AdditionalProperties, null ,exclusions ); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.PowerShell.cs b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.PowerShell.cs new file mode 100644 index 000000000000..97419cb90749 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.PowerShell.cs @@ -0,0 +1,152 @@ +// 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.MonitoringSolutions.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(MonitoringSolutionsIdentityTypeConverter))] + public partial class MonitoringSolutionsIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new MonitoringSolutionsIdentity(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.MonitoringSolutions.Models.IMonitoringSolutionsIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new MonitoringSolutionsIdentity(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.MonitoringSolutions.Models.IMonitoringSolutionsIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal MonitoringSolutionsIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementAssociationName = (string) content.GetValueForProperty("ManagementAssociationName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementAssociationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementConfigurationName = (string) content.GetValueForProperty("ManagementConfigurationName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementConfigurationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ProviderName = (string) content.GetValueForProperty("ProviderName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ProviderName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceType = (string) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SolutionName = (string) content.GetValueForProperty("SolutionName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SolutionName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal MonitoringSolutionsIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).Id, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementAssociationName = (string) content.GetValueForProperty("ManagementAssociationName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementAssociationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementConfigurationName = (string) content.GetValueForProperty("ManagementConfigurationName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ManagementConfigurationName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ProviderName = (string) content.GetValueForProperty("ProviderName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ProviderName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceName = (string) content.GetValueForProperty("ResourceName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceType = (string) content.GetValueForProperty("ResourceType",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).ResourceType, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SolutionName = (string) content.GetValueForProperty("SolutionName",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SolutionName, global::System.Convert.ToString); + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal)this).SubscriptionId, 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.MonitoringSolutions.Runtime.SerializationMode.IncludeAll)?.ToString(); + } + [System.ComponentModel.TypeConverter(typeof(MonitoringSolutionsIdentityTypeConverter))] + public partial interface IMonitoringSolutionsIdentity + + { + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.TypeConverter.cs b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.TypeConverter.cs new file mode 100644 index 000000000000..097e62051cc3 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.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.MonitoringSolutions.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class MonitoringSolutionsIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity 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 MonitoringSolutionsIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return MonitoringSolutionsIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return MonitoringSolutionsIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return MonitoringSolutionsIdentity.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/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.cs b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.cs new file mode 100644 index 000000000000..271853f6c370 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.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. +// 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.MonitoringSolutions.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + public partial class MonitoringSolutionsIdentity : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentityInternal + { + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _managementAssociationName; + + /// User ManagementAssociation Name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ManagementAssociationName { get => this._managementAssociationName; set => this._managementAssociationName = value; } + + /// Backing field for property. + private string _managementConfigurationName; + + /// User Management Configuration Name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ManagementConfigurationName { get => this._managementConfigurationName; set => this._managementConfigurationName = value; } + + /// Backing field for property. + private string _providerName; + + /// Provider name for the parent resource. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ProviderName { get => this._providerName; set => this._providerName = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to get. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _resourceName; + + /// Parent resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ResourceName { get => this._resourceName; set => this._resourceName = value; } + + /// Backing field for property. + private string _resourceType; + + /// Resource type for the parent resource + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string ResourceType { get => this._resourceType; set => this._resourceType = value; } + + /// Backing field for property. + private string _solutionName; + + /// User Solution Name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string SolutionName { get => this._solutionName; set => this._solutionName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Origin(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public MonitoringSolutionsIdentity() + { + + } + } + public partial interface IMonitoringSolutionsIdentity : + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IJsonSerializable + { + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// User ManagementAssociation Name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User ManagementAssociation Name.", + SerializedName = @"managementAssociationName", + PossibleTypes = new [] { typeof(string) })] + string ManagementAssociationName { get; set; } + /// User Management Configuration Name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User Management Configuration Name.", + SerializedName = @"managementConfigurationName", + PossibleTypes = new [] { typeof(string) })] + string ManagementConfigurationName { get; set; } + /// Provider name for the parent resource. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Provider name for the parent resource.", + SerializedName = @"providerName", + PossibleTypes = new [] { typeof(string) })] + string ProviderName { get; set; } + /// The name of the resource group to get. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The name of the resource group to get. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + string ResourceGroupName { get; set; } + /// Parent resource name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Parent resource name.", + SerializedName = @"resourceName", + PossibleTypes = new [] { typeof(string) })] + string ResourceName { get; set; } + /// Resource type for the parent resource + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource type for the parent resource", + SerializedName = @"resourceType", + PossibleTypes = new [] { typeof(string) })] + string ResourceType { get; set; } + /// User Solution Name. + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User Solution Name.", + SerializedName = @"solutionName", + PossibleTypes = new [] { typeof(string) })] + string SolutionName { get; set; } + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface IMonitoringSolutionsIdentityInternal + + { + /// Resource identity path + string Id { get; set; } + /// User ManagementAssociation Name. + string ManagementAssociationName { get; set; } + /// User Management Configuration Name. + string ManagementConfigurationName { get; set; } + /// Provider name for the parent resource. + string ProviderName { get; set; } + /// The name of the resource group to get. The name is case insensitive. + string ResourceGroupName { get; set; } + /// Parent resource name. + string ResourceName { get; set; } + /// Resource type for the parent resource + string ResourceType { get; set; } + /// User Solution Name. + string SolutionName { get; set; } + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.json.cs b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.json.cs new file mode 100644 index 000000000000..fa938ad3a449 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/Models/MonitoringSolutionsIdentity.json.cs @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// 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.MonitoringSolutions.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + public partial class MonitoringSolutionsIdentity + { + + /// + /// 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.MonitoringSolutions.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json erialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json ? new MonitoringSolutionsIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject instance to deserialize from. + internal MonitoringSolutionsIdentity(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)Id;} + {_managementAssociationName = If( json?.PropertyT("managementAssociationName"), out var __jsonManagementAssociationName) ? (string)__jsonManagementAssociationName : (string)ManagementAssociationName;} + {_managementConfigurationName = If( json?.PropertyT("managementConfigurationName"), out var __jsonManagementConfigurationName) ? (string)__jsonManagementConfigurationName : (string)ManagementConfigurationName;} + {_providerName = If( json?.PropertyT("providerName"), out var __jsonProviderName) ? (string)__jsonProviderName : (string)ProviderName;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)ResourceGroupName;} + {_resourceName = If( json?.PropertyT("resourceName"), out var __jsonResourceName) ? (string)__jsonResourceName : (string)ResourceName;} + {_resourceType = If( json?.PropertyT("resourceType"), out var __jsonResourceType) ? (string)__jsonResourceType : (string)ResourceType;} + {_solutionName = If( json?.PropertyT("solutionName"), out var __jsonSolutionName) ? (string)__jsonSolutionName : (string)SolutionName;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)SubscriptionId;} + 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.MonitoringSolutions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AddIf( null != (((object)this._managementAssociationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._managementAssociationName.ToString()) : null, "managementAssociationName" ,container.Add ); + AddIf( null != (((object)this._managementConfigurationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._managementConfigurationName.ToString()) : null, "managementConfigurationName" ,container.Add ); + AddIf( null != (((object)this._providerName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._providerName.ToString()) : null, "providerName" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._resourceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._resourceName.ToString()) : null, "resourceName" ,container.Add ); + AddIf( null != (((object)this._resourceType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._resourceType.ToString()) : null, "resourceType" ,container.Add ); + AddIf( null != (((object)this._solutionName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._solutionName.ToString()) : null, "solutionName" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/api/MonitoringSolutions.cs b/src/MonitoringSolutions/generated/api/MonitoringSolutions.cs new file mode 100644 index 000000000000..80f6345ed4e4 --- /dev/null +++ b/src/MonitoringSolutions/generated/api/MonitoringSolutions.cs @@ -0,0 +1,2585 @@ +// 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.MonitoringSolutions +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// Low-level API implementation for the MonitoringSolutions service. + /// + public partial class MonitoringSolutions + { + + /// Creates or updates the ManagementAssociation. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// Provider name for the parent resource. + /// Resource type for the parent resource + /// Parent resource name. + /// User ManagementAssociation Name. + /// The parameters required to create ManagementAssociation extension. + /// 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.MonitoringSolutions.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 ManagementAssociationsCreateOrUpdate(string subscriptionId, string resourceGroupName, string providerName, string resourceType, string resourceName, string managementAssociationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/" + + global::System.Uri.EscapeDataString(providerName) + + "/" + + global::System.Uri.EscapeDataString(resourceType) + + "/" + + global::System.Uri.EscapeDataString(resourceName) + + "/providers/Microsoft.OperationsManagement/ManagementAssociations/" + + global::System.Uri.EscapeDataString(managementAssociationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Creates or updates the ManagementAssociation. + /// + /// The parameters required to create ManagementAssociation extension. + /// 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.MonitoringSolutions.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 ManagementAssociationsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementAssociations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{providerName}/{resourceType}/{resourceName}/providers/Microsoft.OperationsManagement/ManagementAssociations/{managementAssociationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var providerName = _match.Groups["providerName"].Value; + var resourceType = _match.Groups["resourceType"].Value; + var resourceName = _match.Groups["resourceName"].Value; + var managementAssociationName = _match.Groups["managementAssociationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/" + + providerName + + "/" + + resourceType + + "/" + + resourceName + + "/providers/Microsoft.OperationsManagement/ManagementAssociations/" + + managementAssociationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementAssociationsCreateOrUpdate_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociation.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// Provider name for the parent resource. + /// Resource type for the parent resource + /// Parent resource name. + /// User ManagementAssociation Name. + /// The parameters required to create ManagementAssociation extension. + /// 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 ManagementAssociationsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string providerName, string resourceType, string resourceName, string managementAssociationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementAssociation body, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(providerName),providerName); + await eventListener.AssertNotNull(nameof(resourceType),resourceType); + await eventListener.AssertNotNull(nameof(resourceName),resourceName); + await eventListener.AssertNotNull(nameof(managementAssociationName),managementAssociationName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the ManagementAssociation in the subscription. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// Provider name for the parent resource. + /// Resource type for the parent resource + /// Parent resource name. + /// User ManagementAssociation Name. + /// 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.MonitoringSolutions.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 ManagementAssociationsDelete(string subscriptionId, string resourceGroupName, string providerName, string resourceType, string resourceName, string managementAssociationName, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/" + + global::System.Uri.EscapeDataString(providerName) + + "/" + + global::System.Uri.EscapeDataString(resourceType) + + "/" + + global::System.Uri.EscapeDataString(resourceName) + + "/providers/Microsoft.OperationsManagement/ManagementAssociations/" + + global::System.Uri.EscapeDataString(managementAssociationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsDelete_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Deletes the ManagementAssociation in the subscription. + /// + /// 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.MonitoringSolutions.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 ManagementAssociationsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementAssociations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{providerName}/{resourceType}/{resourceName}/providers/Microsoft.OperationsManagement/ManagementAssociations/{managementAssociationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var providerName = _match.Groups["providerName"].Value; + var resourceType = _match.Groups["resourceType"].Value; + var resourceName = _match.Groups["resourceName"].Value; + var managementAssociationName = _match.Groups["managementAssociationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/" + + providerName + + "/" + + resourceType + + "/" + + resourceName + + "/providers/Microsoft.OperationsManagement/ManagementAssociations/" + + managementAssociationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsDelete_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementAssociationsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// Provider name for the parent resource. + /// Resource type for the parent resource + /// Parent resource name. + /// User ManagementAssociation Name. + /// 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 ManagementAssociationsDelete_Validate(string subscriptionId, string resourceGroupName, string providerName, string resourceType, string resourceName, string managementAssociationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(providerName),providerName); + await eventListener.AssertNotNull(nameof(resourceType),resourceType); + await eventListener.AssertNotNull(nameof(resourceName),resourceName); + await eventListener.AssertNotNull(nameof(managementAssociationName),managementAssociationName); + } + } + + /// Retrieves the user ManagementAssociation. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// Provider name for the parent resource. + /// Resource type for the parent resource + /// Parent resource name. + /// User ManagementAssociation Name. + /// 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.MonitoringSolutions.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 ManagementAssociationsGet(string subscriptionId, string resourceGroupName, string providerName, string resourceType, string resourceName, string managementAssociationName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/" + + global::System.Uri.EscapeDataString(providerName) + + "/" + + global::System.Uri.EscapeDataString(resourceType) + + "/" + + global::System.Uri.EscapeDataString(resourceName) + + "/providers/Microsoft.OperationsManagement/ManagementAssociations/" + + global::System.Uri.EscapeDataString(managementAssociationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Retrieves the user ManagementAssociation. + /// + /// 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.MonitoringSolutions.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 ManagementAssociationsGetViaIdentity(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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/(?[^/]+)/(?[^/]+)/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementAssociations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{providerName}/{resourceType}/{resourceName}/providers/Microsoft.OperationsManagement/ManagementAssociations/{managementAssociationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var providerName = _match.Groups["providerName"].Value; + var resourceType = _match.Groups["resourceType"].Value; + var resourceName = _match.Groups["resourceName"].Value; + var managementAssociationName = _match.Groups["managementAssociationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/" + + providerName + + "/" + + resourceType + + "/" + + resourceName + + "/providers/Microsoft.OperationsManagement/ManagementAssociations/" + + managementAssociationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementAssociationsGet_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociation.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// Provider name for the parent resource. + /// Resource type for the parent resource + /// Parent resource name. + /// User ManagementAssociation Name. + /// 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 ManagementAssociationsGet_Validate(string subscriptionId, string resourceGroupName, string providerName, string resourceType, string resourceName, string managementAssociationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(providerName),providerName); + await eventListener.AssertNotNull(nameof(resourceType),resourceType); + await eventListener.AssertNotNull(nameof(resourceName),resourceName); + await eventListener.AssertNotNull(nameof(managementAssociationName),managementAssociationName); + } + } + + /// Retrieves the ManagementAssociations list. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// 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.MonitoringSolutions.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 ManagementAssociationsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.OperationsManagement/ManagementAssociations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Retrieves the ManagementAssociations list. + /// + /// 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.MonitoringSolutions.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 ManagementAssociationsListBySubscriptionViaIdentity(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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementAssociations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.OperationsManagement/ManagementAssociations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.OperationsManagement/ManagementAssociations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementAssociationsListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementAssociationsListBySubscription_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementAssociationPropertiesList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// 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 ManagementAssociationsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Creates or updates the ManagementConfiguration. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Management Configuration Name. + /// The parameters required to create OMS Solution. + /// 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.MonitoringSolutions.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 ManagementConfigurationsCreateOrUpdate(string subscriptionId, string resourceGroupName, string managementConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations/" + + global::System.Uri.EscapeDataString(managementConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Creates or updates the ManagementConfiguration. + /// + /// The parameters required to create OMS Solution. + /// 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.MonitoringSolutions.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 ManagementConfigurationsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementConfigurations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/ManagementConfigurations/{managementConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var managementConfigurationName = _match.Groups["managementConfigurationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations/" + + managementConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsCreateOrUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementConfigurationsCreateOrUpdate_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Management Configuration Name. + /// The parameters required to create OMS Solution. + /// 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 ManagementConfigurationsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string managementConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IManagementConfiguration body, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(managementConfigurationName),managementConfigurationName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the ManagementConfiguration in the subscription. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Management Configuration Name. + /// 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.MonitoringSolutions.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 ManagementConfigurationsDelete(string subscriptionId, string resourceGroupName, string managementConfigurationName, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations/" + + global::System.Uri.EscapeDataString(managementConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsDelete_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Deletes the ManagementConfiguration in the subscription. + /// + /// 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.MonitoringSolutions.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 ManagementConfigurationsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementConfigurations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/ManagementConfigurations/{managementConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var managementConfigurationName = _match.Groups["managementConfigurationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations/" + + managementConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsDelete_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementConfigurationsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Management Configuration Name. + /// 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 ManagementConfigurationsDelete_Validate(string subscriptionId, string resourceGroupName, string managementConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(managementConfigurationName),managementConfigurationName); + } + } + + /// Retrieves the user ManagementConfiguration. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Management Configuration Name. + /// 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.MonitoringSolutions.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 ManagementConfigurationsGet(string subscriptionId, string resourceGroupName, string managementConfigurationName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations/" + + global::System.Uri.EscapeDataString(managementConfigurationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Retrieves the user ManagementConfiguration. + /// + /// 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.MonitoringSolutions.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 ManagementConfigurationsGetViaIdentity(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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementConfigurations/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/ManagementConfigurations/{managementConfigurationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var managementConfigurationName = _match.Groups["managementConfigurationName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations/" + + managementConfigurationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementConfigurationsGet_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Management Configuration Name. + /// 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 ManagementConfigurationsGet_Validate(string subscriptionId, string resourceGroupName, string managementConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(managementConfigurationName),managementConfigurationName); + } + } + + /// Retrieves the ManagementConfigurations list. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// 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.MonitoringSolutions.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 ManagementConfigurationsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Retrieves the ManagementConfigurations list. + /// + /// 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.MonitoringSolutions.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 ManagementConfigurationsListBySubscriptionViaIdentity(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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.OperationsManagement/ManagementConfigurations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.OperationsManagement/ManagementConfigurations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.OperationsManagement/ManagementConfigurations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.ManagementConfigurationsListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 ManagementConfigurationsListBySubscription_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ManagementConfigurationPropertiesList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// 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 ManagementConfigurationsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Lists all of the available OperationsManagement Rest API operations. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.OperationsManagement/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,eventListener,sender); + } + } + + /// Lists all of the available OperationsManagement Rest API operations. + /// + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.OperationsManagement/operations$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.OperationsManagement/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/providers/Microsoft.OperationsManagement/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call(request,onOk,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + throw new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException(_response); + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// Creates or updates the Solution. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// The parameters required to create OMS Solution. + /// 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.MonitoringSolutions.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 SolutionsCreateOrUpdate(string subscriptionId, string resourceGroupName, string solutionName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution body, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/solutions/" + + global::System.Uri.EscapeDataString(solutionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsCreateOrUpdate_Call(request,onCreated,onDefault,eventListener,sender); + } + } + + /// Creates or updates the Solution. + /// + /// The parameters required to create OMS Solution. + /// 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.MonitoringSolutions.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 SolutionsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution body, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/solutions/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var solutionName = _match.Groups["solutionName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/solutions/" + + solutionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsCreateOrUpdate_Call(request,onCreated,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// 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.MonitoringSolutions.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 SolutionsCreateOrUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Solution.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// The parameters required to create OMS Solution. + /// 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 SolutionsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string solutionName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution body, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(solutionName),solutionName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Deletes the solution in the subscription. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// 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.MonitoringSolutions.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 SolutionsDelete(string subscriptionId, string resourceGroupName, string solutionName, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/solutions/" + + global::System.Uri.EscapeDataString(solutionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsDelete_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Deletes the solution in the subscription. + /// + /// 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.MonitoringSolutions.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 SolutionsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/solutions/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var solutionName = _match.Groups["solutionName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/solutions/" + + solutionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsDelete_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 SolutionsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// 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 SolutionsDelete_Validate(string subscriptionId, string resourceGroupName, string solutionName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(solutionName),solutionName); + } + } + + /// Retrieves the user solution. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// 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.MonitoringSolutions.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 SolutionsGet(string subscriptionId, string resourceGroupName, string solutionName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/solutions/" + + global::System.Uri.EscapeDataString(solutionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Retrieves the user solution. + /// + /// 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.MonitoringSolutions.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 SolutionsGetViaIdentity(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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/solutions/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var solutionName = _match.Groups["solutionName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/solutions/" + + solutionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsGet_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 SolutionsGet_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Solution.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// 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 SolutionsGet_Validate(string subscriptionId, string resourceGroupName, string solutionName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(solutionName),solutionName); + } + } + + /// + /// Retrieves the solution list. It will retrieve both first party and third party solutions + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// 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.MonitoringSolutions.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 SolutionsListByResourceGroup(string subscriptionId, string resourceGroupName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/solutions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Retrieves the solution list. It will retrieve both first party and third party solutions + /// + /// + /// 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.MonitoringSolutions.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 SolutionsListByResourceGroupViaIdentity(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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/solutions$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/solutions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsListByResourceGroup_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 SolutionsListByResourceGroup_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPropertiesList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// 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 SolutionsListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + } + } + + /// + /// Retrieves the solution list. It will retrieve both first party and third party solutions + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// 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.MonitoringSolutions.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 SolutionsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.OperationsManagement/solutions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// + /// Retrieves the solution list. It will retrieve both first party and third party solutions + /// + /// + /// 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.MonitoringSolutions.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 SolutionsListBySubscriptionViaIdentity(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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Microsoft.OperationsManagement/solutions$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.OperationsManagement/solutions'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/providers/Microsoft.OperationsManagement/solutions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsListBySubscription_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 SolutionsListBySubscription_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPropertiesList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// 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 SolutionsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Update the tags of a solution. + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// The parameters required to patch a Solution. + /// 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.MonitoringSolutions.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 SolutionsUpdate(string subscriptionId, string resourceGroupName, string solutionName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourcegroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.OperationsManagement/solutions/" + + global::System.Uri.EscapeDataString(solutionName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Update the tags of a solution. + /// + /// The parameters required to patch a Solution. + /// 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.MonitoringSolutions.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 SolutionsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + var apiVersion = @"2015-11-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourcegroups/(?[^/]+)/providers/Microsoft.OperationsManagement/solutions/(?[^/]+)$").Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var solutionName = _match.Groups["solutionName"].Value; + // construct URL + var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( + "https://management.azure.com/subscriptions/" + + subscriptionId + + "/resourcegroups/" + + resourceGroupName + + "/providers/Microsoft.OperationsManagement/solutions/" + + solutionName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.SolutionsUpdate_Call(request,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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 SolutionsUpdate_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.MonitoringSolutions.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Solution.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.CodeMessageError.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription + /// ID forms part of the URI for every service call. + /// The name of the resource group to get. The name is case insensitive. + /// User Solution Name. + /// The parameters required to patch a Solution. + /// 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 SolutionsUpdate_Validate(string subscriptionId, string resourceGroupName, string solutionName, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch body, Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertMinimumLength(nameof(resourceGroupName),resourceGroupName,1); + await eventListener.AssertMaximumLength(nameof(resourceGroupName),resourceGroupName,90); + await eventListener.AssertRegEx(nameof(resourceGroupName),resourceGroupName,@"^[-\w\._\(\)]+$"); + await eventListener.AssertNotNull(nameof(solutionName),solutionName); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsOperation_List.cs b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsOperation_List.cs new file mode 100644 index 000000000000..67838d32c190 --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsOperation_List.cs @@ -0,0 +1,297 @@ +// 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.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Lists all of the available OperationsManagement Rest API operations. + /// + /// [OpenAPI] Operations_List=>GET:"/providers/Microsoft.OperationsManagement/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMonitorLogAnalyticsOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Lists all of the available OperationsManagement Rest API operations.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class GetAzMonitorLogAnalyticsOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzMonitorLogAnalyticsOperation_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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // pageable / value / + WriteObject((await response).Value, true); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_Get.cs b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_Get.cs new file mode 100644 index 000000000000..1ac979aa6519 --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_Get.cs @@ -0,0 +1,402 @@ +// 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.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Retrieves the user solution. + /// + /// [OpenAPI] Solutions_Get=>GET:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMonitorLogAnalyticsSolution_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Retrieves the user solution.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class GetAzMonitorLogAnalyticsSolution_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// User Solution Name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "User Solution Name.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"User Solution Name.", + SerializedName = @"solutionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SolutionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to get. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to get. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to get. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzMonitorLogAnalyticsSolution_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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SolutionsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_GetViaIdentity.cs b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_GetViaIdentity.cs new file mode 100644 index 000000000000..d207d0a73f24 --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_GetViaIdentity.cs @@ -0,0 +1,377 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Retrieves the user solution. + /// + /// [OpenAPI] Solutions_Get=>GET:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMonitorLogAnalyticsSolution_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Retrieves the user solution.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class GetAzMonitorLogAnalyticsSolution_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzMonitorLogAnalyticsSolution_GetViaIdentity() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SolutionsGetViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SolutionName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SolutionName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SolutionsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SolutionName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_List.cs b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_List.cs new file mode 100644 index 000000000000..700d6c086a8c --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_List.cs @@ -0,0 +1,390 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// Retrieves the solution list. It will retrieve both first party and third party solutions + /// + /// + /// [OpenAPI] Solutions_ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMonitorLogAnalyticsSolution_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Retrieves the solution list. It will retrieve both first party and third party solutions")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class GetAzMonitorLogAnalyticsSolution_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to get. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to get. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to get. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzMonitorLogAnalyticsSolution_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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SolutionsListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // nested-array / value / + WriteObject((await response).Value, true); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_List1.cs b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_List1.cs new file mode 100644 index 000000000000..c004a9fae3ae --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/GetAzMonitorLogAnalyticsSolution_List1.cs @@ -0,0 +1,376 @@ +// 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.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// + /// Retrieves the solution list. It will retrieve both first party and third party solutions + /// + /// + /// [OpenAPI] Solutions_ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.OperationsManagement/solutions" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMonitorLogAnalyticsSolution_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Retrieves the solution list. It will retrieve both first party and third party solutions")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class GetAzMonitorLogAnalyticsSolution_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public GetAzMonitorLogAnalyticsSolution_List1() + { + + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SolutionsListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // response should be returning an array of some kind. +Pageable + // nested-array / value / + WriteObject((await response).Value, true); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/NewAzMonitorLogAnalyticsSolution_CreateExpanded.cs b/src/MonitoringSolutions/generated/cmdlets/NewAzMonitorLogAnalyticsSolution_CreateExpanded.cs new file mode 100644 index 000000000000..99b6d63ac9cf --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/NewAzMonitorLogAnalyticsSolution_CreateExpanded.cs @@ -0,0 +1,524 @@ +// 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.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Creates or updates the Solution. + /// + /// [OpenAPI] Solutions_CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMonitorLogAnalyticsSolution_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Creates or updates the Solution.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class NewAzMonitorLogAnalyticsSolution_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when + /// the solution is deleted. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when the solution is deleted.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The azure resources that will be contained within the solutions. They will be locked and gets deleted automatically when the solution is deleted.", + SerializedName = @"containedResources", + PossibleTypes = new [] { typeof(string) })] + public string[] ContainedResource { get => ParametersBody.ContainedResource ?? null /* arrayOf */; set => ParametersBody.ContainedResource = value; } + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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; } } + + /// Resource location + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource location", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => ParametersBody.Location ?? null; set => ParametersBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// User Solution Name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "User Solution Name.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"User Solution Name.", + SerializedName = @"solutionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SolutionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.Solution(); + + /// The container for solution. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). + /// SolutionType part is case sensitive. For third party solution, it can be anything. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). SolutionType part is case sensitive. For third party solution, it can be anything.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"name of the solution to be created. For Microsoft published solution it should be in the format of solutionType(workspaceName). SolutionType part is case sensitive. For third party solution, it can be anything.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + public string PlanName { get => ParametersBody.PlanName ?? null; set => ParametersBody.PlanName = value; } + + /// + /// name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. + /// This is case sensitive + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. This is case sensitive")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"name of the solution to enabled/add. For Microsoft published gallery solution it should be in the format of OMSGallery/. This is case sensitive", + SerializedName = @"product", + PossibleTypes = new [] { typeof(string) })] + public string PlanProduct { get => ParametersBody.PlanProduct ?? null; set => ParametersBody.PlanProduct = value; } + + /// promotionCode, Not really used now, can you left as empty + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "promotionCode, Not really used now, can you left as empty")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"promotionCode, Not really used now, can you left as empty", + SerializedName = @"promotionCode", + PossibleTypes = new [] { typeof(string) })] + public string PlanPromotionCode { get => ParametersBody.PlanPromotionCode ?? null; set => ParametersBody.PlanPromotionCode = value; } + + /// Publisher name. For gallery solution, it is Microsoft. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher name. For gallery solution, it is Microsoft.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher name. For gallery solution, it is Microsoft.", + SerializedName = @"publisher", + PossibleTypes = new [] { typeof(string) })] + public string PlanPublisher { get => ParametersBody.PlanPublisher ?? null; set => ParametersBody.PlanPublisher = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution. + /// + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The resources that will be referenced from this solution. Deleting any of those solution out of band will break the solution.", + SerializedName = @"referencedResources", + PossibleTypes = new [] { typeof(string) })] + public string[] ReferencedResource { get => ParametersBody.ReferencedResource ?? null /* arrayOf */; set => ParametersBody.ReferencedResource = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to get. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to get. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to get. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } + + /// + /// The azure resourceId for the workspace where the solution will be deployed/enabled. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The azure resourceId for the workspace where the solution will be deployed/enabled.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The azure resourceId for the workspace where the solution will be deployed/enabled.", + SerializedName = @"workspaceResourceId", + PossibleTypes = new [] { typeof(string) })] + public string WorkspaceResourceId { get => ParametersBody.WorkspaceResourceId ?? null; set => ParametersBody.WorkspaceResourceId = value; } + + /// + /// 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 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 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public NewAzMonitorLogAnalyticsSolution_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SolutionsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SolutionsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, ParametersBody, onCreated, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// 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 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.MonitoringSolutions.Models.Api20151101Preview.ISolution + WriteObject((await response)); + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/RemoveAzMonitorLogAnalyticsSolution_Delete.cs b/src/MonitoringSolutions/generated/cmdlets/RemoveAzMonitorLogAnalyticsSolution_Delete.cs new file mode 100644 index 000000000000..fe3f1cc4e0e5 --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/RemoveAzMonitorLogAnalyticsSolution_Delete.cs @@ -0,0 +1,407 @@ +// 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.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Deletes the solution in the subscription. + /// + /// [OpenAPI] Solutions_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzMonitorLogAnalyticsSolution_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Deletes the solution in the subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class RemoveAzMonitorLogAnalyticsSolution_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// User Solution Name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "User Solution Name.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"User Solution Name.", + SerializedName = @"solutionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SolutionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to get. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to get. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to get. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SolutionsDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SolutionsDelete(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzMonitorLogAnalyticsSolution_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/RemoveAzMonitorLogAnalyticsSolution_DeleteViaIdentity.cs b/src/MonitoringSolutions/generated/cmdlets/RemoveAzMonitorLogAnalyticsSolution_DeleteViaIdentity.cs new file mode 100644 index 000000000000..a46a780106e4 --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/RemoveAzMonitorLogAnalyticsSolution_DeleteViaIdentity.cs @@ -0,0 +1,385 @@ +// 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.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Deletes the solution in the subscription. + /// + /// [OpenAPI] Solutions_Delete=>DELETE:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzMonitorLogAnalyticsSolution_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Deletes the solution in the subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class RemoveAzMonitorLogAnalyticsSolution_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SolutionsDelete' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SolutionsDeleteViaIdentity(InputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SolutionName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SolutionName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SolutionsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SolutionName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public RemoveAzMonitorLogAnalyticsSolution_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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. + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/UpdateAzMonitorLogAnalyticsSolution_UpdateExpanded.cs b/src/MonitoringSolutions/generated/cmdlets/UpdateAzMonitorLogAnalyticsSolution_UpdateExpanded.cs new file mode 100644 index 000000000000..b94d25c7a241 --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/UpdateAzMonitorLogAnalyticsSolution_UpdateExpanded.cs @@ -0,0 +1,420 @@ +// 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.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Update the tags of a solution. + /// + /// [OpenAPI] Solutions_Update=>PATCH:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMonitorLogAnalyticsSolution_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Update the tags of a solution.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class UpdateAzMonitorLogAnalyticsSolution_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// User Solution Name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "User Solution Name.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"User Solution Name.", + SerializedName = @"solutionName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("SolutionName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatch(); + + /// The properties of a Solution that can be patched. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group to get. The name is case insensitive. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group to get. The name is case insensitive.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the resource group to get. The name is case insensitive.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// + /// Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of + /// the URI for every service call. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.")] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SolutionsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.SolutionsUpdate(SubscriptionId, ResourceGroupName, Name, ParametersBody, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzMonitorLogAnalyticsSolution_UpdateExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/cmdlets/UpdateAzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded.cs b/src/MonitoringSolutions/generated/cmdlets/UpdateAzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded.cs new file mode 100644 index 000000000000..62ac601825ef --- /dev/null +++ b/src/MonitoringSolutions/generated/cmdlets/UpdateAzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded.cs @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Extensions; + + /// Update the tags of a solution. + /// + /// [OpenAPI] Solutions_Update=>PATCH:"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Description(@"Update the tags of a solution.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Generated] + public partial class UpdateAzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.MonitoringSolutions Client => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.ClientAPI; + + /// + /// The credentials, account, tenant, and subscription used for communication with Azure + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.SolutionPatch(); + + /// The properties of a Solution that can be patched. + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatch ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } + + /// + /// The instance of the that the remote call will use. + /// + private Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Resource tags + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionPatchTags Tag { get => ParametersBody.Tag ?? null /* object */; set => ParametersBody.Tag = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data, new[] { data.Message }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.Error: + { + WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'SolutionsUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.SolutionsUpdateViaIdentity(InputObject.Id, ParametersBody, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.SolutionName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SolutionName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.SolutionsUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.SolutionName ?? null, ParametersBody, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Intializes a new instance of the cmdlet class. + /// + public UpdateAzMonitorLogAnalyticsSolution_UpdateViaIdentityExpanded() + { + + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution + WriteObject((await response)); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/AsyncCommandRuntime.cs b/src/MonitoringSolutions/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 000000000000..9c7f443b7ed5 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,828 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/AsyncJob.cs b/src/MonitoringSolutions/generated/runtime/AsyncJob.cs new file mode 100644 index 000000000000..a8bb5c24a15d --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/AsyncOperationResponse.cs b/src/MonitoringSolutions/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 000000000000..7239ad32e8c5 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter to the parameter using and + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 000000000000..488b3cba4fb8 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 000000000000..c951a11663eb --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 000000000000..3c3b03f35aa1 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,99 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Support"; + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!IsAzure || pf.Property.Name != "Id") + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = viewParameters.Type.FullName + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 000000000000..164dca544e18 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 000000000000..d8ca9a81cdad --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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.MonitoringSolutions.Models"; + private const string SupportNamespace = @"Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Support"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 000000000000..2392b1b1226d --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,159 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + protected override void ProcessRecord() + { + try { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append(@" +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +"); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder); + } + } + } catch (Exception ee) { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 000000000000..65b5f555ca56 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.0"); + // 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.MonitoringSolutions.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: MonitoringSolutions cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.MonitoringSolutions.private.dll"}'"); + + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.MonitoringSolutions.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().Append("*").ToPsList(); + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = {previewVersion}"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule MonitoringSolutions".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/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 000000000000..5a02cdf06991 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,137 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine(@"$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath)" +); + sb.AppendLine($@"$TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@"$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName +"); + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 000000000000..59316bb410da --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 000000000000..c86b28fb73cc --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 000000000000..a08bb591216b --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/CollectionExtensions.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 000000000000..70ec330caa23 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/BuildTime/MarkdownRenderer.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 000000000000..f271fe7fc63a --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,121 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + if (markdownInfo.SupportsPaging) + { + foreach (var parameter in SupportsPagingParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"### {alias}{Environment.NewLine}{Environment.NewLine}"); + } + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"{relatedLink}{Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 000000000000..4fe28aacafcc --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 000000000000..deec5ddc88e2 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,177 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() => $@"{ExampleNameHeader}{ExampleInfo.Name} +{ExampleCodeHeader} +{ExampleInfo.Code} +{ExampleCodeFooter} + +{ExampleInfo.Description.ToDescriptionFormat()} + +"; + } + + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Description.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 000000000000..8963a27ed2f9 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 000000000000..aec7ed180b48 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,291 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public string[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + RelatedLinks = commentInfo.RelatedLinks; + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (codeEndIndex ?? 0) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + if (Variant.SupportsPaging) + { + parameterStrings = parameterStrings.Append(" [-First ]").Append(" [-IncludeTotalCount]").Append(" [-Skip ]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string description) + { + Name = name; + Code = code; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"PS C:\> {{{{ Add code here }}}}{Environment.NewLine}{Environment.NewLine}{{{{ Add output here }}}}", @"{{ Add description here }}") + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 000000000000..5ae976eb1d0c --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,513 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BeginOutput + { + public VariantGroup VariantGroup { get; } + + public BeginOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}')) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + return sb.ToString(); + } + } + + internal class ProcessOutput + { + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} + +"; + } + + internal class EndOutput + { + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{Indent}}} catch {{ +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new [] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new []{"
", "\r\n", "\n"}); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => new ArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, !isFirst && includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 000000000000..ce36e6a7a65d --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,499 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}To construct, see NOTES section for {complexParameterName} properties and create a hash table."; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines().Replace(complexMessage, String.Empty).Replace(complexMessage.ToPsSingleLine(), String.Empty); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[]{} : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + + private const string HelpLinkPrefix = @"https://docs.microsoft.com/en-us/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{variantGroup.ModuleName.ToLowerInvariant()}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => !ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)); + } + return parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))).ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/PsAttributes.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 000000000000..bb4990212cf3 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/PsExtensions.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 000000000000..26e3039fdf00 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,160 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal static class PsExtensions + { + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/PsHelpers.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 000000000000..a905d3abe1d4 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path '{scriptFolder}' -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.StartsWith(GuidStart))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/BuildTime/StringExtensions.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 000000000000..177be5f5f2cf --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/BuildTime/XmlExtensions.cs b/src/MonitoringSolutions/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 000000000000..28ca59503275 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/CmdInfoHandler.cs b/src/MonitoringSolutions/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 000000000000..cf2b3bf20e6d --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/ConversionException.cs b/src/MonitoringSolutions/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 000000000000..e1ad9ce2d1d1 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/IJsonConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 000000000000..18efe18a2fa9 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Conversions/Instances/BinaryConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 000000000000..d3d6f2f9e50c --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/BooleanConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 000000000000..adf784f20a6e --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 000000000000..703a780690de --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 000000000000..e0bd5445abca --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/DecimalConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 000000000000..76bdd1051421 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/DoubleConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 000000000000..6089371236a0 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/EnumConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 000000000000..39c85f45a575 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/GuidConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 000000000000..afe308fa517c --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 000000000000..3b6932a23901 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/Int16Converter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 000000000000..3337d00d3fc0 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/Int32Converter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 000000000000..9d1019e00931 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/Int64Converter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 000000000000..08a43055a26f --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 000000000000..95901ade0ba6 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 000000000000..3e0332253eb0 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/SingleConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 000000000000..c7242f834b20 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/StringConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 000000000000..fc0c68d93d81 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 000000000000..caf48a6d3096 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/UInt16Converter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 000000000000..9a5fdb16afe2 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/UInt32Converter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 000000000000..96eab7e23831 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/UInt64Converter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 000000000000..ae36c1958aed --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/Instances/UriConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 000000000000..b474bc2233b2 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/JsonConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 000000000000..ee441139b967 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/JsonConverterAttribute.cs b/src/MonitoringSolutions/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 000000000000..1c954880f71b --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/JsonConverterFactory.cs b/src/MonitoringSolutions/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 000000000000..424ff40987e4 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Conversions/StringLikeConverter.cs b/src/MonitoringSolutions/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 000000000000..642fc518c5bb --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Customizations/IJsonSerializable.cs b/src/MonitoringSolutions/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 000000000000..3093dda32151 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Customizations/JsonArray.cs b/src/MonitoringSolutions/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 000000000000..61827496f3fd --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Customizations/JsonBoolean.cs b/src/MonitoringSolutions/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 000000000000..e78bc51994a3 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Customizations/JsonNode.cs b/src/MonitoringSolutions/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 000000000000..ef238957a11d --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Customizations/JsonNumber.cs b/src/MonitoringSolutions/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 000000000000..83369c4d795a --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Customizations/JsonObject.cs b/src/MonitoringSolutions/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 000000000000..239644280a08 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Customizations/JsonString.cs b/src/MonitoringSolutions/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 000000000000..fba5d1b69e56 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Customizations/XNodeArray.cs b/src/MonitoringSolutions/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 000000000000..7b51c01c7461 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Debugging.cs b/src/MonitoringSolutions/generated/runtime/Debugging.cs new file mode 100644 index 000000000000..4d67819f0117 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/DictionaryExtensions.cs b/src/MonitoringSolutions/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 000000000000..0c987c043ff8 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + if (value is System.Collections.Hashtable nested) + { + HashTableToDictionary(nested, new System.Collections.Generic.Dictionary()); + } + else + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/EventData.cs b/src/MonitoringSolutions/generated/runtime/EventData.cs new file mode 100644 index 000000000000..46321b3661a7 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/EventDataExtensions.cs b/src/MonitoringSolutions/generated/runtime/EventDataExtensions.cs new file mode 100644 index 000000000000..43e7e05dc931 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime +{ + using System; + + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/EventListener.cs b/src/MonitoringSolutions/generated/runtime/EventListener.cs new file mode 100644 index 000000000000..0260d77162b7 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Events.cs b/src/MonitoringSolutions/generated/runtime/Events.cs new file mode 100644 index 000000000000..e8414ea9ddfe --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/EventsExtensions.cs b/src/MonitoringSolutions/generated/runtime/EventsExtensions.cs new file mode 100644 index 000000000000..e8e81f4d5ea4 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Extensions.cs b/src/MonitoringSolutions/generated/runtime/Extensions.cs new file mode 100644 index 000000000000..0c59464248d3 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/Extensions.cs @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + using System.Linq; + + internal static partial class Extensions + { + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => headerName == each.Key).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/src/MonitoringSolutions/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 000000000000..2b16bb89be9f --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/src/MonitoringSolutions/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 000000000000..fdb229ee8216 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Helpers/Seperator.cs b/src/MonitoringSolutions/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 000000000000..0d4e212ee4ba --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Helpers/TypeDetails.cs b/src/MonitoringSolutions/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 000000000000..570d41cc7a7d --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Helpers/XHelper.cs b/src/MonitoringSolutions/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 000000000000..222643072f93 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/HttpPipeline.cs b/src/MonitoringSolutions/generated/runtime/HttpPipeline.cs new file mode 100644 index 000000000000..189367a3a303 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/HttpPipelineMocking.ps1 b/src/MonitoringSolutions/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 000000000000..bec43d1020eb --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/IAssociativeArray.cs b/src/MonitoringSolutions/generated/runtime/IAssociativeArray.cs new file mode 100644 index 000000000000..f0129331eb1f --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,21 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + int Count { get; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/IHeaderSerializable.cs b/src/MonitoringSolutions/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 000000000000..bd9727444a59 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/ISendAsync.cs b/src/MonitoringSolutions/generated/runtime/ISendAsync.cs new file mode 100644 index 000000000000..3034163ce88b --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/ISendAsync.cs @@ -0,0 +1,289 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/InfoAttribute.cs b/src/MonitoringSolutions/generated/runtime/InfoAttribute.cs new file mode 100644 index 000000000000..73f114e25260 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/InfoAttribute.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Iso/IsoDate.cs b/src/MonitoringSolutions/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 000000000000..2887f020fdc0 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/JsonType.cs b/src/MonitoringSolutions/generated/runtime/JsonType.cs new file mode 100644 index 000000000000..e5c61315cdff --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Method.cs b/src/MonitoringSolutions/generated/runtime/Method.cs new file mode 100644 index 000000000000..1d6529c8f277 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Models/JsonMember.cs b/src/MonitoringSolutions/generated/runtime/Models/JsonMember.cs new file mode 100644 index 000000000000..fcaf6c34d30d --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Models/JsonModel.cs b/src/MonitoringSolutions/generated/runtime/Models/JsonModel.cs new file mode 100644 index 000000000000..1516280bc479 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Models/JsonModelCache.cs b/src/MonitoringSolutions/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 000000000000..f4671240a83e --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/Collections/JsonArray.cs b/src/MonitoringSolutions/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 000000000000..4e6aa5a487f7 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/Collections/XImmutableArray.cs b/src/MonitoringSolutions/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 000000000000..68bcfb9c3c6b --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/Collections/XList.cs b/src/MonitoringSolutions/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 000000000000..cdf555b2a473 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/Collections/XNodeArray.cs b/src/MonitoringSolutions/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 000000000000..0a80502ecb3b --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,68 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Nodes/Collections/XSet.cs b/src/MonitoringSolutions/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 000000000000..2a3583965620 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/JsonBoolean.cs b/src/MonitoringSolutions/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 000000000000..44365de67ae2 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/JsonDate.cs b/src/MonitoringSolutions/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 000000000000..0543acae8d0c --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/JsonNode.cs b/src/MonitoringSolutions/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 000000000000..a2e7cc87247b --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/JsonNumber.cs b/src/MonitoringSolutions/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 000000000000..1635ffbc7e8e --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Nodes/JsonObject.cs b/src/MonitoringSolutions/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 000000000000..1195092bd94c --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/JsonString.cs b/src/MonitoringSolutions/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 000000000000..18a2a1ac5401 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/XBinary.cs b/src/MonitoringSolutions/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 000000000000..b1f7a105dc4a --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Nodes/XNull.cs b/src/MonitoringSolutions/generated/runtime/Nodes/XNull.cs new file mode 100644 index 000000000000..a361a9e9faef --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Parser/Exceptions/ParseException.cs b/src/MonitoringSolutions/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 000000000000..976a1ec1ff7f --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Parser/JsonParser.cs b/src/MonitoringSolutions/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 000000000000..1acf69fbcf08 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Parser/JsonToken.cs b/src/MonitoringSolutions/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 000000000000..c0561e826ea7 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Parser/JsonTokenizer.cs b/src/MonitoringSolutions/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 000000000000..3e30478cabc0 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Parser/Location.cs b/src/MonitoringSolutions/generated/runtime/Parser/Location.cs new file mode 100644 index 000000000000..063763d6a090 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Parser/Readers/SourceReader.cs b/src/MonitoringSolutions/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 000000000000..51141ff29af0 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Parser/TokenReader.cs b/src/MonitoringSolutions/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 000000000000..1c2dc863a08a --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/PipelineMocking.cs b/src/MonitoringSolutions/generated/runtime/PipelineMocking.cs new file mode 100644 index 000000000000..a665a5a847e8 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/PipelineMocking.cs @@ -0,0 +1,254 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result); + + internal static JsonNode SerializeContent(byte[] content) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (content.EndsWith("==")) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content) }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content) }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"))) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"))) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Response.cs b/src/MonitoringSolutions/generated/runtime/Response.cs new file mode 100644 index 000000000000..270a43593ce8 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Serialization/JsonSerializer.cs b/src/MonitoringSolutions/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 000000000000..596b212c927e --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Serialization/PropertyTransformation.cs b/src/MonitoringSolutions/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 000000000000..13e879fedb27 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/Serialization/SerializationOptions.cs b/src/MonitoringSolutions/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 000000000000..b9fa9ce87d4e --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/SerializationMode.cs b/src/MonitoringSolutions/generated/runtime/SerializationMode.cs new file mode 100644 index 000000000000..c33cdc22f0f8 --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/SerializationMode.cs @@ -0,0 +1,16 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeReadOnly = 1 << 1, + + IncludeAll = IncludeHeaders | IncludeReadOnly + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/TypeConverterExtensions.cs b/src/MonitoringSolutions/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 000000000000..73a07db6c92e --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,190 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + } +} diff --git a/src/MonitoringSolutions/generated/runtime/UndeclaredResponseException.cs b/src/MonitoringSolutions/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 000000000000..e8f3a0feb60c --- /dev/null +++ b/src/MonitoringSolutions/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,104 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Json.JsonObject; + + // see if there is an error block in the body + json = json.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // we'll create one below. + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/generated/runtime/Writers/JsonWriter.cs b/src/MonitoringSolutions/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 000000000000..e09db93e23e1 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/generated/runtime/delegates.cs b/src/MonitoringSolutions/generated/runtime/delegates.cs new file mode 100644 index 000000000000..4e16d0895e41 --- /dev/null +++ b/src/MonitoringSolutions/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.MonitoringSolutions.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/MonitoringSolutions/help/Az.MonitoringSolutions.md b/src/MonitoringSolutions/help/Az.MonitoringSolutions.md new file mode 100644 index 000000000000..0c668b798bbc --- /dev/null +++ b/src/MonitoringSolutions/help/Az.MonitoringSolutions.md @@ -0,0 +1,25 @@ +--- +Module Name: Az.MonitoringSolutions +Module Guid: 4e0cdc62-833e-41bd-aa97-f8f042986de3 +Download Help Link: https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions +Help Version: 1.0.0.0 +Locale: en-US +--- + +# Az.MonitoringSolutions Module +## Description +Microsoft Azure PowerShell: MonitoringSolutions cmdlets + +## Az.MonitoringSolutions Cmdlets +### [Get-AzMonitorLogAnalyticsSolution](Get-AzMonitorLogAnalyticsSolution.md) +Retrieves the user solution. + +### [New-AzMonitorLogAnalyticsSolution](New-AzMonitorLogAnalyticsSolution.md) +Creates a log analytics solution. + +### [Remove-AzMonitorLogAnalyticsSolution](Remove-AzMonitorLogAnalyticsSolution.md) +Deletes the solution in the subscription. + +### [Update-AzMonitorLogAnalyticsSolution](Update-AzMonitorLogAnalyticsSolution.md) +Update the tags of a solution. + diff --git a/src/MonitoringSolutions/help/Get-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/help/Get-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..8b52424e9f34 --- /dev/null +++ b/src/MonitoringSolutions/help/Get-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,213 @@ +--- +external help file: +Module Name: Az.MonitoringSolutions +online version: https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/get-azmonitorloganalyticssolution +schema: 2.0.0 +--- + +# Get-AzMonitorLogAnalyticsSolution + +## SYNOPSIS +Retrieves the user solution. + +## SYNTAX + +### List1 (Default) +``` +Get-AzMonitorLogAnalyticsSolution [-SubscriptionId ] [-DefaultProfile ] + [] +``` + +### Get +``` +Get-AzMonitorLogAnalyticsSolution -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [] +``` + +### GetViaIdentity +``` +Get-AzMonitorLogAnalyticsSolution -InputObject [-DefaultProfile ] + [] +``` + +### List +``` +Get-AzMonitorLogAnalyticsSolution -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [] +``` + +## DESCRIPTION +Retrieves the user solution. + +## EXAMPLES + +### Example 1: Get a monitor log analytics solution by name +```powershell +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets a monitor log analytics solution by name. + +### Example 2: Get a monitor log analytics solution by resource id +```powershell +PS C:\> @{Id = "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/azureps-manual-test/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-t01)"} | Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +``` + +This command gets a monitor log analytics solution by resource id. + +### Example 3: Get a monitor log analytics solution by object +```powershell + +PS C:\> $monitor = New-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor -Name 'Containers(azureps-monitor)' +PS C:\> Get-AzMonitorLogAnalyticsSolution -InputObject $monitor +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets a monitor log analytics solution by object. + +### Example 4: Get all monitor log analytics solutions under a resource group +```powershell +PS C:\> Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-monitor + +Name Type Location +---- ---- -------- +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets all monitor log analytics solutions under a resource group. + +### Example 5: Get all monitor log analytics solutions under a subscription +```powershell +PS C:\> Get-AzMonitorLogAnalyticsSolution + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-t01) Microsoft.OperationsManagement/solutions East US +Containers(azureps-monitor) Microsoft.OperationsManagement/solutions West US 2 +``` + +This command gets all monitor log analytics solutions under a subscription. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +Parameter Sets: GetViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +User Solution Name. + +```yaml +Type: System.String +Parameter Sets: Get +Aliases: SolutionName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to get. +The name is case insensitive. + +```yaml +Type: System.String +Parameter Sets: Get, List +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Gets subscription credentials which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String[] +Parameter Sets: Get, List, List1 +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[ManagementAssociationName ]`: User ManagementAssociation Name. + - `[ManagementConfigurationName ]`: User Management Configuration Name. + - `[ProviderName ]`: Provider name for the parent resource. + - `[ResourceGroupName ]`: The name of the resource group to get. The name is case insensitive. + - `[ResourceName ]`: Parent resource name. + - `[ResourceType ]`: Resource type for the parent resource + - `[SolutionName ]`: User Solution Name. + - `[SubscriptionId ]`: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + +## RELATED LINKS + diff --git a/src/MonitoringSolutions/help/New-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/help/New-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..59ae7ef88772 --- /dev/null +++ b/src/MonitoringSolutions/help/New-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,219 @@ +--- +external help file: +Module Name: Az.MonitoringSolutions +online version: https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/new-azmonitorloganalyticssolution +schema: 2.0.0 +--- + +# New-AzMonitorLogAnalyticsSolution + +## SYNOPSIS +Creates a log analytics solution. + +## SYNTAX + +``` +New-AzMonitorLogAnalyticsSolution -ResourceGroupName -Location -Type + -WorkspaceResourceId [-SubscriptionId ] [-Tag ] [-DefaultProfile ] + [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Creates a log analytics solution. + +## EXAMPLES + +### Example 1: Create a monitor log analytics solution for the log analytics workspace +```powershell +PS C:\> $workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName azureps-manual-test -Name monitoringworkspace-2vob7n +PS C:\> New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName azureps-manual-test -Location $workspace.Location -WorkspaceResourceId $workspace.ResourceId + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +``` + +This command creates a monitor log analytics solution for the log analytics workspace. + +Commonly used types are: + +| Type | Description | +| :-----| :----- | +| SecurityCenterFree | Azure Security Center – Free Edition | +| Security | Azure Security Center | +| Updates | Update Management | +| ContainerInsights | Azure Monitor for Containers | +| ServiceMap | Service Map | +| AzureActivity | Activity log analytics | +| ChangeTracking | Change tracking and inventory | +| VMInsights | Azure Monitor for VMs | +| SecurityInsights | Azure Sentinel | +| NetworkMonitoring | Network Performance Monitor | +| SQLVulnerabilityAssessment | SQL Vulnerability Assessment | +| SQLAdvancedThreatProtection | SQL Advanced Threat Protection | +| AntiMalware | Antimalware Assessment | +| AzureAutomation | Automation Hybrid Worker | +| LogicAppsManagement | Logic Apps Management | +| SQLDataClassification | SQL Data Discovery & Classification | + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Location +Resource location. +Must be the same as the log analytic workspace. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to get. +The name is case insensitive. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Gets subscription credentials which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +Resource tags + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Type +Type of the solution to be created. +For example "Container". + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: SolutionType + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WorkspaceResourceId +The Azure resource ID for the workspace where the solution will be deployed/enabled. + +```yaml +Type: System.String +Parameter Sets: (All) +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 + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution + +## NOTES + +ALIASES + +## RELATED LINKS + + + +[Get-AzOperationalInsightsWorkspace](https://docs.microsoft.com/en-us/powershell/module/az.operationalinsights/get-azoperationalinsightsworkspace) + diff --git a/src/MonitoringSolutions/help/Remove-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/help/Remove-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..54486c03fa1a --- /dev/null +++ b/src/MonitoringSolutions/help/Remove-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,215 @@ +--- +external help file: +Module Name: Az.MonitoringSolutions +online version: https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/remove-azmonitorloganalyticssolution +schema: 2.0.0 +--- + +# Remove-AzMonitorLogAnalyticsSolution + +## SYNOPSIS +Deletes the solution in the subscription. + +## SYNTAX + +### Delete (Default) +``` +Remove-AzMonitorLogAnalyticsSolution -Name -ResourceGroupName [-SubscriptionId ] + [-DefaultProfile ] [-PassThru] [-Confirm] [-WhatIf] [] +``` + +### DeleteViaIdentity +``` +Remove-AzMonitorLogAnalyticsSolution -InputObject [-DefaultProfile ] + [-PassThru] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Deletes the solution in the subscription. + +## EXAMPLES + +### Example 1: Remove a monitor log analytics solution by name +```powershell +PS C:\> Remove-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' + +``` + +This command removes a monitor log analytics solution by name. + +### Example 2: Remove a monitor log analytics solution by object +```powershell +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-pevful)' +PS C:\> Remove-AzMonitorLogAnalyticsSolution -InputObject $monitor + +``` + +This command removes a monitor log analytics solution by object. + +### Example 3: Remove a monitor log analytics solution by pipeline +```powershell +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName azureps-manual-test -Name 'Containers(monitoringworkspace-asdehu)' | Remove-AzMonitorLogAnalyticsSolution + +``` + +This command removes a monitor log analytics solution by pipeline. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +Parameter Sets: DeleteViaIdentity +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +User Solution Name. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: SolutionName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PassThru +Returns true when the command succeeds + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to get. +The name is case insensitive. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Gets subscription credentials which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: Delete +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity + +## OUTPUTS + +### System.Boolean + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[ManagementAssociationName ]`: User ManagementAssociation Name. + - `[ManagementConfigurationName ]`: User Management Configuration Name. + - `[ProviderName ]`: Provider name for the parent resource. + - `[ResourceGroupName ]`: The name of the resource group to get. The name is case insensitive. + - `[ResourceName ]`: Parent resource name. + - `[ResourceType ]`: Resource type for the parent resource + - `[SolutionName ]`: User Solution Name. + - `[SubscriptionId ]`: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + +## RELATED LINKS + diff --git a/src/MonitoringSolutions/help/Update-AzMonitorLogAnalyticsSolution.md b/src/MonitoringSolutions/help/Update-AzMonitorLogAnalyticsSolution.md new file mode 100644 index 000000000000..1dd0185410f9 --- /dev/null +++ b/src/MonitoringSolutions/help/Update-AzMonitorLogAnalyticsSolution.md @@ -0,0 +1,213 @@ +--- +external help file: +Module Name: Az.MonitoringSolutions +online version: https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/update-azmonitorloganalyticssolution +schema: 2.0.0 +--- + +# Update-AzMonitorLogAnalyticsSolution + +## SYNOPSIS +Update the tags of a solution. + +## SYNTAX + +### UpdateExpanded (Default) +``` +Update-AzMonitorLogAnalyticsSolution -Name -ResourceGroupName [-SubscriptionId ] + [-Tag ] [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +### UpdateViaIdentityExpanded +``` +Update-AzMonitorLogAnalyticsSolution -InputObject [-Tag ] + [-DefaultProfile ] [-Confirm] [-WhatIf] [] +``` + +## DESCRIPTION +Update the tags of a solution. + +## EXAMPLES + +### Example 1: Update a monitor log analytics solution by name +```powershell +PS C:\> Update-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +``` + +This command updates a monitor log analytics solution by name. + +### Example 2: Update a monitor log analytics solution by object +```powershell +PS C:\> $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName lucas-manual-test -Name 'Containers(monitoringworkspace-2vob7n)' +PS C:\> Update-AzMonitorLogAnalyticsSolution -InputObject $monitor -Tag @{'Operation'='update';'Param'='Tag'} + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US +``` + +This command updates a monitor log analytics solution by object. + +## PARAMETERS + +### -DefaultProfile +The credentials, account, tenant, and subscription used for communication with Azure. + +```yaml +Type: System.Management.Automation.PSObject +Parameter Sets: (All) +Aliases: AzureRMContext, AzureCredential + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InputObject +Identity Parameter +To construct, see NOTES section for INPUTOBJECT properties and create a hash table. + +```yaml +Type: Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity +Parameter Sets: UpdateViaIdentityExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Name +User Solution Name. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: SolutionName + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResourceGroupName +The name of the resource group to get. +The name is case insensitive. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SubscriptionId +Gets subscription credentials which uniquely identify Microsoft Azure subscription. +The subscription ID forms part of the URI for every service call. + +```yaml +Type: System.String +Parameter Sets: UpdateExpanded +Aliases: + +Required: False +Position: Named +Default value: (Get-AzContext).Subscription.Id +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tag +Resource tags + +```yaml +Type: System.Collections.Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.IMonitoringSolutionsIdentity + +## OUTPUTS + +### Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution + +## NOTES + +ALIASES + +COMPLEX PARAMETER PROPERTIES + +To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables. + + +INPUTOBJECT : Identity Parameter + - `[Id ]`: Resource identity path + - `[ManagementAssociationName ]`: User ManagementAssociation Name. + - `[ManagementConfigurationName ]`: User Management Configuration Name. + - `[ProviderName ]`: Provider name for the parent resource. + - `[ResourceGroupName ]`: The name of the resource group to get. The name is case insensitive. + - `[ResourceName ]`: Parent resource name. + - `[ResourceType ]`: Resource type for the parent resource + - `[SolutionName ]`: User Solution Name. + - `[SubscriptionId ]`: Gets subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + +## RELATED LINKS + diff --git a/src/MonitoringSolutions/how-to.md b/src/MonitoringSolutions/how-to.md new file mode 100644 index 000000000000..f0a23dd30160 --- /dev/null +++ b/src/MonitoringSolutions/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.MonitoringSolutions`. + +## Building `Az.MonitoringSolutions` +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.MonitoringSolutions` +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.MonitoringSolutions` +To pack `Az.MonitoringSolutions` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://docs.microsoft.com/en-us/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.MonitoringSolutions`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.MonitoringSolutions.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.MonitoringSolutions.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.MonitoringSolutions`. + - `-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.MonitoringSolutions` 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/MonitoringSolutions/internal/Az.MonitoringSolutions.internal.psm1 b/src/MonitoringSolutions/internal/Az.MonitoringSolutions.internal.psm1 new file mode 100644 index 000000000000..cd88fac4c2d2 --- /dev/null +++ b/src/MonitoringSolutions/internal/Az.MonitoringSolutions.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.MonitoringSolutions.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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/MonitoringSolutions/internal/Get-AzMonitorLogAnalyticsOperation.ps1 b/src/MonitoringSolutions/internal/Get-AzMonitorLogAnalyticsOperation.ps1 new file mode 100644 index 000000000000..972fae5f8ed1 --- /dev/null +++ b/src/MonitoringSolutions/internal/Get-AzMonitorLogAnalyticsOperation.ps1 @@ -0,0 +1,121 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists all of the available OperationsManagement Rest API operations. +.Description +Lists all of the available OperationsManagement Rest API operations. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/get-azmonitorloganalyticsoperation +#> +function Get-AzMonitorLogAnalyticsOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsOperation_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/MonitoringSolutions/internal/New-AzMonitorLogAnalyticsSolution.ps1 b/src/MonitoringSolutions/internal/New-AzMonitorLogAnalyticsSolution.ps1 new file mode 100644 index 000000000000..fc3685c3a718 --- /dev/null +++ b/src/MonitoringSolutions/internal/New-AzMonitorLogAnalyticsSolution.ps1 @@ -0,0 +1,208 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates or updates the Solution. +.Description +Creates or updates the Solution. +.Example +PS C:\> $workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName azureps-manual-test -Name monitoringworkspace-2vob7n +PS C:\> New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName azureps-manual-test -Location $workspace.Location -WorkspaceResourceId $workspace.ResourceId + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/new-azmonitorloganalyticssolution +#> +function New-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String[]] + # The azure resources that will be contained within the solutions. + # They will be locked and gets deleted automatically when the solution is deleted. + ${ContainedResource}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Resource location + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # name of the solution to be created. + # For Microsoft published solution it should be in the format of solutionType(workspaceName). + # SolutionType part is case sensitive. + # For third party solution, it can be anything. + ${PlanName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # name of the solution to enabled/add. + # For Microsoft published gallery solution it should be in the format of OMSGallery/. + # This is case sensitive + ${PlanProduct}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # promotionCode, Not really used now, can you left as empty + ${PlanPromotionCode}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Publisher name. + # For gallery solution, it is Microsoft. + ${PlanPublisher}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String[]] + # The resources that will be referenced from this solution. + # Deleting any of those solution out of band will break the solution. + ${ReferencedResource}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # The azure resourceId for the workspace where the solution will be deployed/enabled. + ${WorkspaceResourceId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.MonitoringSolutions.private\New-AzMonitorLogAnalyticsSolution_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/MonitoringSolutions/internal/ProxyCmdletDefinitions.ps1 b/src/MonitoringSolutions/internal/ProxyCmdletDefinitions.ps1 new file mode 100644 index 000000000000..7fb7e6994dbc --- /dev/null +++ b/src/MonitoringSolutions/internal/ProxyCmdletDefinitions.ps1 @@ -0,0 +1,329 @@ + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Lists all of the available OperationsManagement Rest API operations. +.Description +Lists all of the available OperationsManagement Rest API operations. +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} +.Example +PS C:\> {{ Add code here }} + +{{ Add output here }} + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/get-azmonitorloganalyticsoperation +#> +function Get-AzMonitorLogAnalyticsOperation { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.IOperation])] +[CmdletBinding(DefaultParameterSetName='List', PositionalBinding=$false)] +param( + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.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.MonitoringSolutions.private\Get-AzMonitorLogAnalyticsOperation_List'; + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} + +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Creates or updates the Solution. +.Description +Creates or updates the Solution. +.Example +PS C:\> $workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName azureps-manual-test -Name monitoringworkspace-2vob7n +PS C:\> New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName azureps-manual-test -Location $workspace.Location -WorkspaceResourceId $workspace.ResourceId + +Name Type Location +---- ---- -------- +Containers(monitoringworkspace-2vob7n) Microsoft.OperationsManagement/solutions East US + +.Outputs +Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution +.Link +https://docs.microsoft.com/en-us/powershell/module/az.monitoringsolutions/new-azmonitorloganalyticssolution +#> +function New-AzMonitorLogAnalyticsSolution { +[OutputType([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolution])] +[CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] +param( + [Parameter(Mandatory)] + [Alias('SolutionName')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # User Solution Name. + ${Name}, + + [Parameter(Mandatory)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [System.String] + # The name of the resource group to get. + # The name is case insensitive. + ${ResourceGroupName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # Gets subscription credentials which uniquely identify Microsoft Azure subscription. + # The subscription ID forms part of the URI for every service call. + ${SubscriptionId}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String[]] + # The azure resources that will be contained within the solutions. + # They will be locked and gets deleted automatically when the solution is deleted. + ${ContainedResource}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Resource location + ${Location}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # name of the solution to be created. + # For Microsoft published solution it should be in the format of solutionType(workspaceName). + # SolutionType part is case sensitive. + # For third party solution, it can be anything. + ${PlanName}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # name of the solution to enabled/add. + # For Microsoft published gallery solution it should be in the format of OMSGallery/. + # This is case sensitive + ${PlanProduct}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # promotionCode, Not really used now, can you left as empty + ${PlanPromotionCode}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # Publisher name. + # For gallery solution, it is Microsoft. + ${PlanPublisher}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String[]] + # The resources that will be referenced from this solution. + # Deleting any of those solution out of band will break the solution. + ${ReferencedResource}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Models.Api20151101Preview.ISolutionTags]))] + [System.Collections.Hashtable] + # Resource tags + ${Tag}, + + [Parameter()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Body')] + [System.String] + # The azure resourceId for the workspace where the solution will be deployed/enabled. + ${WorkspaceResourceId}, + + [Parameter()] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Azure')] + [System.Management.Automation.PSObject] + # The credentials, account, tenant, and subscription used for communication with Azure. + ${DefaultProfile}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Wait for .NET debugger to attach + ${Break}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be appended to the front of the pipeline + ${HttpPipelineAppend}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Runtime.SendAsyncStep[]] + # SendAsync Pipeline Steps to be prepended to the front of the pipeline + ${HttpPipelinePrepend}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Uri] + # The URI for the proxy server to use + ${Proxy}, + + [Parameter(DontShow)] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.PSCredential] + # Credentials for a proxy server to use for the remote call + ${ProxyCredential}, + + [Parameter(DontShow)] + [Microsoft.Azure.PowerShell.Cmdlets.MonitoringSolutions.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Use the default credentials for the proxy + ${ProxyUseDefaultCredentials} +) + +begin { + try { + $outBuffer = $null + if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { + $PSBoundParameters['OutBuffer'] = 1 + } + $parameterSet = $PSCmdlet.ParameterSetName + $mapping = @{ + CreateExpanded = 'Az.MonitoringSolutions.private\New-AzMonitorLogAnalyticsSolution_CreateExpanded'; + } + if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { + $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id + } + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) + $scriptCmd = {& $wrappedCmd @PSBoundParameters} + $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) + $steppablePipeline.Begin($PSCmdlet) + } catch { + throw + } +} + +process { + try { + $steppablePipeline.Process($_) + } catch { + throw + } +} + +end { + try { + $steppablePipeline.End() + } catch { + throw + } +} +} diff --git a/src/MonitoringSolutions/internal/readme.md b/src/MonitoringSolutions/internal/readme.md new file mode 100644 index 000000000000..6111d036f23f --- /dev/null +++ b/src/MonitoringSolutions/internal/readme.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.MonitoringSolutions.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.MonitoringSolutions`. Instead, this sub-module is imported by the `..\custom\Az.MonitoringSolutions.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.MonitoringSolutions.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.MonitoringSolutions`. \ No newline at end of file diff --git a/src/MonitoringSolutions/pack-module.ps1 b/src/MonitoringSolutions/pack-module.ps1 new file mode 100644 index 000000000000..c22fad33d87b --- /dev/null +++ b/src/MonitoringSolutions/pack-module.ps1 @@ -0,0 +1,16 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/MonitoringSolutions/readme.md b/src/MonitoringSolutions/readme.md new file mode 100644 index 000000000000..32b7b6a6d286 --- /dev/null +++ b/src/MonitoringSolutions/readme.md @@ -0,0 +1,96 @@ + +# Az.MonitoringSolutions +This directory contains the PowerShell module for the MonitoringSolutions service. + +--- +## Status +[![Az.MonitoringSolutions](https://img.shields.io/powershellgallery/v/Az.MonitoringSolutions.svg?style=flat-square&label=Az.MonitoringSolutions "Az.MonitoringSolutions")](https://www.powershellgallery.com/packages/Az.MonitoringSolutions/) + +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 1.8.1 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.MonitoringSolutions`, see [how-to.md](how-to.md). + + +## Generation Requirements +Use of the beta version of `autorest.powershell` generator requires the following: +- [NodeJS LTS](https://nodejs.org) (10.15.x LTS preferred) + - **Note**: It *will not work* with Node < 10.x. Using 11.x builds may cause issues as they may introduce instability or breaking changes. +> If you want an easy way to install and update Node, [NVS - Node Version Switcher](../nodejs/installing-via-nvs.md) or [NVM - Node Version Manager](../nodejs/installing-via-nvm.md) is recommended. +- [AutoRest](https://aka.ms/autorest) v3 beta
`npm install -g autorest@autorest`
  +- PowerShell 6.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g pwsh`
  +- .NET Core SDK 2.0 or greater + - If you don't have it installed, you can use the cross-platform npm package
`npm install -g dotnet-sdk-2.2`
  + +## Run Generation +In this directory, run AutoRest: +> `autorest-beta` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +``` yaml +require: + - $(this-folder)/../readme.azure.noprofile.md +input-file: + - https://github.com/Azure/azure-rest-api-specs/blob/740a40ba31720ad514a308054ba517a8ea956a3c/specification/operationsmanagement/resource-manager/Microsoft.OperationsManagement/preview/2015-11-01-preview/OperationsManagement.json + +module-version: 0.1.0 +title: MonitoringSolutions +subject-prefix: MonitorLogAnalytics + +inlining-threshold: 40 + +directive: + # Fix error in swagger: PUT, PATCH, DELETE of solutions are not long running + - from: swagger-document + where: $ + # ": " is a special term in yaml, indicating a key-value pair. Needs to use ":\ " to prevent grammar error. + transform: return $.replace(/"x-ms-long-running-operation":\ true/g, "\"x-ms-long-running-operation\":\ false") + # Remove the unexpanded parameter set + - where: + variant: ^Create$|^CreateViaIdentity$|^CreateViaIdentityExpanded$|^Update$|^UpdateViaIdentity$ + remove: true + # Remove the set-* cmdlet + - where: + verb: Set + remove: true + # Remove the cmdlets we don't need for now + - where: + subject: Association$|Configuration$ + remove: true + # Hide New-*Solution for customization + - where: + verb: New + subject: Solution$ + hide: true + - where: + model-name: Solution + set: + format-table: + properties: + - Name + - Type + - Location + + # Update the cmdlet description of Update-AzMonitorLogAnalyticsSolution + - from: swagger-document + where: $.paths["/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationsManagement/solutions/{solutionName}"].patch.description + transform: return "Update the tags of a solution." +``` diff --git a/src/MonitoringSolutions/run-module.ps1 b/src/MonitoringSolutions/run-module.ps1 new file mode 100644 index 000000000000..953bf61fd019 --- /dev/null +++ b/src/MonitoringSolutions/run-module.ps1 @@ -0,0 +1,59 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.MonitoringSolutions.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/MonitoringSolutions/test-module.ps1 b/src/MonitoringSolutions/test-module.ps1 new file mode 100644 index 000000000000..3941037cf6b0 --- /dev/null +++ b/src/MonitoringSolutions/test-module.ps1 @@ -0,0 +1,68 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +param([switch]$Isolated, [switch]$Live, [switch]$Record, [switch]$Playback) +$ErrorActionPreference = 'Stop' + +if(-not $Isolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -Isolated + return +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -Isolated -Accounts:$false -Pester -Resources:$requireResourceModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) { + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.MonitoringSolutions.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +if($Live) { + $TestMode = 'live' +} +if($Record) { + $TestMode = 'record' +} +try { + if ($TestMode -ne 'playback') { + setupEnv + } + $testFolder = Join-Path $PSScriptRoot 'test' + Invoke-Pester -Script @{ Path = $testFolder } -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") +} +Finally +{ + if ($TestMode -ne 'playback') { + cleanupEnv + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/src/MonitoringSolutions/test/Get-AzMonitorLogAnalyticsSolution.Recording.json b/src/MonitoringSolutions/test/Get-AzMonitorLogAnalyticsSolution.Recording.json new file mode 100644 index 000000000000..321720799c44 --- /dev/null +++ b/src/MonitoringSolutions/test/Get-AzMonitorLogAnalyticsSolution.Recording.json @@ -0,0 +1,209 @@ +{ + "Get-AzMonitorLogAnalyticsSolution+[NoContext]+List1+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "3" ], + "x-ms-client-request-id": [ "7c6ea449-2ce3-4d44-bff8-b4b96284b1ce" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_List1" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "x-ms-original-request-ids": [ "6f984b52-60d2-43b5-8262-93a8ee2203cb", "d7f9dcbc-7796-4054-9fb2-72f36ffaf59c" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11995" ], + "x-ms-request-id": [ "3674ed73-b925-423d-8b31-68c711adeebb" ], + "x-ms-correlation-request-id": [ "3674ed73-b925-423d-8b31-68c711adeebb" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065707Z:3674ed73-b925-423d-8b31-68c711adeebb" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Date": [ "Tue, 30 Jun 2020 06:57:07 GMT" ] + }, + "ContentHeaders": { + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ], + "Content-Length": [ "5748" ] + }, + "Content": "{\"value\":[{\"plan\":{\"name\":\"Containers(monitoringworkspace-t01)\",\"publisher\":\"Microsoft\",\"promotionCode\":\"\",\"product\":\"OMSGallery/Containers\"},\"properties\":{\"workspaceResourceId\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-t01\",\"provisioningState\":\"Succeeded\",\"creationTime\":\"Sun, 28 Jun 2020 03:13:17 GMT\",\"lastModifiedTime\":\"Sun, 28 Jun 2020 03:44:06 GMT\",\"containedResources\":[\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-t01/views/Containers(monitoringworkspace-t01)\"]},\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-t01)\",\"name\":\"Containers(monitoringworkspace-t01)\",\"type\":\"Microsoft.OperationsManagement/solutions\",\"location\":\"East US\",\"tags\":{\"key03\":\"3\",\"key01\":\"1\",\"key02\":\"2\"}},{\"plan\":{\"name\":\"Security(monitoringworkspace-t01)\",\"publisher\":\"Microsoft\",\"promotionCode\":\"\",\"product\":\"OMSGallery/Security\"},\"properties\":{\"workspaceResourceId\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-t01\",\"provisioningState\":\"Succeeded\",\"creationTime\":\"Tue, 30 Jun 2020 06:35:27 GMT\",\"lastModifiedTime\":\"Tue, 30 Jun 2020 06:35:27 GMT\",\"containedResources\":[\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-t01/views/Security(monitoringworkspace-t01)\"]},\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/Microsoft.OperationsManagement/solutions/Security(monitoringworkspace-t01)\",\"name\":\"Security(monitoringworkspace-t01)\",\"type\":\"Microsoft.OperationsManagement/solutions\",\"location\":\"East US\"},{\"plan\":{\"name\":\"SecurityCenterFree(monitoringworkspace-t01)\",\"publisher\":\"Microsoft\",\"promotionCode\":\"\",\"product\":\"OMSGallery/SecurityCenterFree\"},\"properties\":{\"workspaceResourceId\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-t01\",\"provisioningState\":\"Succeeded\",\"creationTime\":\"Tue, 30 Jun 2020 06:33:04 GMT\",\"lastModifiedTime\":\"Tue, 30 Jun 2020 06:33:04 GMT\",\"containedResources\":[]},\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/Microsoft.OperationsManagement/solutions/SecurityCenterFree(monitoringworkspace-t01)\",\"name\":\"SecurityCenterFree(monitoringworkspace-t01)\",\"type\":\"Microsoft.OperationsManagement/solutions\",\"location\":\"East US\"},{\"plan\":{\"name\":\"Updates(monitoringworkspace-t01)\",\"publisher\":\"Microsoft\",\"promotionCode\":\"\",\"product\":\"OMSGallery/Updates\"},\"properties\":{\"workspaceResourceId\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-t01\",\"provisioningState\":\"Succeeded\",\"creationTime\":\"Tue, 30 Jun 2020 06:35:52 GMT\",\"lastModifiedTime\":\"Tue, 30 Jun 2020 06:35:52 GMT\",\"containedResources\":[\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-t01/views/Updates(monitoringworkspace-t01)\"]},\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/lucas-manual-test/providers/Microsoft.OperationsManagement/solutions/Updates(monitoringworkspace-t01)\",\"name\":\"Updates(monitoringworkspace-t01)\",\"type\":\"Microsoft.OperationsManagement/solutions\",\"location\":\"East US\"},{\"plan\":{\"name\":\"Containers(monitoringworkspace-k5foa9)\",\"publisher\":\"Microsoft\",\"promotionCode\":\"\",\"product\":\"OMSGallery/Containers\"},\"properties\":{\"workspaceResourceId\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\"provisioningState\":\"Succeeded\",\"creationTime\":\"Tue, 30 Jun 2020 06:57:03 GMT\",\"lastModifiedTime\":\"Tue, 30 Jun 2020 06:57:03 GMT\",\"containedResources\":[\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"]},\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\"name\":\"Containers(monitoringworkspace-k5foa9)\",\"type\":\"Microsoft.OperationsManagement/solutions\",\"location\":\"East US\"},{\"plan\":{\"name\":\"Containers(yemingmonitor)\",\"publisher\":\"Microsoft\",\"promotionCode\":\"\",\"product\":\"OMSGallery/Containers\"},\"properties\":{\"workspaceResourceId\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/yemingmonitor/providers/microsoft.operationalinsights/workspaces/yemingmonitor\",\"provisioningState\":\"Succeeded\",\"creationTime\":\"Mon, 08 Jun 2020 08:51:41 GMT\",\"lastModifiedTime\":\"Wed, 17 Jun 2020 08:19:49 GMT\",\"containedResources\":[\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/yemingmonitor/providers/microsoft.operationalinsights/workspaces/yemingmonitor/views/Containers(yemingmonitor)\"]},\"id\":\"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/yemingmonitor/providers/Microsoft.OperationsManagement/solutions/Containers(yemingmonitor)\",\"name\":\"Containers(yemingmonitor)\",\"type\":\"Microsoft.OperationsManagement/solutions\",\"location\":\"West US 2\"}]}" + } + }, + "Get-AzMonitorLogAnalyticsSolution+[NoContext]+Get+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "4" ], + "x-ms-client-request-id": [ "7c9ab025-cc37-4752-8ca6-232aed5257f5" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "cb5dd1ca-86f9-4303-ae0d-6ffa9e170582" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11994" ], + "x-ms-correlation-request-id": [ "79bd7e88-deff-47f4-8c63-6e08984ae79c" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065708Z:79bd7e88-deff-47f4-8c63-6e08984ae79c" ], + "Date": [ "Tue, 30 Jun 2020 06:57:08 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1154" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + }, + "Get-AzMonitorLogAnalyticsSolution+[NoContext]+List+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "5" ], + "x-ms-client-request-id": [ "a451c327-7be8-4c63-91ae-8d6377578bea" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "b3d7f393-ccfe-45ed-89ff-9d893fa32750" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11993" ], + "x-ms-correlation-request-id": [ "f95cf440-2206-4a40-820a-117868c45c0d" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065708Z:f95cf440-2206-4a40-820a-117868c45c0d" ], + "Date": [ "Tue, 30 Jun 2020 06:57:08 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1263" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"value\": [\r\n {\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n }\r\n ]\r\n}" + } + }, + "Get-AzMonitorLogAnalyticsSolution+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "6" ], + "x-ms-client-request-id": [ "a5364bd5-80b8-400c-ab8a-7ec2af270b73" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "5bb98c0a-af7d-4658-9c5b-d9c70538a59d" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11992" ], + "x-ms-correlation-request-id": [ "03e0be88-7046-4eba-a582-8f947a1db348" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065709Z:03e0be88-7046-4eba-a582-8f947a1db348" ], + "Date": [ "Tue, 30 Jun 2020 06:57:09 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1154" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + }, + "Get-AzMonitorLogAnalyticsSolution+[NoContext]+GetViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)?api-version=2015-11-01-preview+2": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "7" ], + "x-ms-client-request-id": [ "a159d7b2-8eab-42e0-8a7d-a177685beb6c" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_GetViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "cc1e1d5d-f0db-4848-8521-f699168c262d" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11991" ], + "x-ms-correlation-request-id": [ "2fe76f89-0d9b-4f34-8263-178512e7820d" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065709Z:2fe76f89-0d9b-4f34-8263-178512e7820d" ], + "Date": [ "Tue, 30 Jun 2020 06:57:09 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1154" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/test/Get-AzMonitorLogAnalyticsSolution.Tests.ps1 b/src/MonitoringSolutions/test/Get-AzMonitorLogAnalyticsSolution.Tests.ps1 new file mode 100644 index 000000000000..697f94cdc4ff --- /dev/null +++ b/src/MonitoringSolutions/test/Get-AzMonitorLogAnalyticsSolution.Tests.ps1 @@ -0,0 +1,35 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Get-AzMonitorLogAnalyticsSolution.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-AzMonitorLogAnalyticsSolution' { + It 'List1' { + $monitorList = Get-AzMonitorLogAnalyticsSolution + $monitorList.Count | Should -BeGreaterOrEqual 1 + } + + It 'Get' { + $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup -Name $env.monitorName01 + $monitor.Name | Should -Be $env.monitorName01 + } + + It 'List' { + $monitorList = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup + $monitorList.Count | Should -Be 1 + } + + It 'GetViaIdentity' { + $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup -Name $env.monitorName01 + $newMonitor = Get-AzMonitorLogAnalyticsSolution -InputObject $monitor + $newMonitor.Name | Should -Be $env.monitorName01 + } +} diff --git a/src/MonitoringSolutions/test/New-AzMonitorLogAnalyticsSolution.Recording.json b/src/MonitoringSolutions/test/New-AzMonitorLogAnalyticsSolution.Recording.json new file mode 100644 index 000000000000..925182173a06 --- /dev/null +++ b/src/MonitoringSolutions/test/New-AzMonitorLogAnalyticsSolution.Recording.json @@ -0,0 +1,150 @@ +{ + "New-AzMonitorLogAnalyticsSolution+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview", + "Content": "{\n \"plan\": {\n \"name\": \"Containers(monitoringworkspace-clihub)\",\n \"product\": \"OMSGallery/Containers\",\n \"promotionCode\": \"\",\n \"publisher\": \"Microsoft\"\n },\n \"properties\": {\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-clihub\"\n },\n \"location\": \"eastus\"\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "418" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "0463450f-16d5-4d2d-8745-6574176ef286" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1189" ], + "x-ms-correlation-request-id": [ "a6b1c738-cce8-43c6-a5ae-eb2abe6cf121" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065713Z:a6b1c738-cce8-43c6-a5ae-eb2abe6cf121" ], + "Date": [ "Tue, 30 Jun 2020 06:57:13 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1154" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-clihub)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-clihub\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"lastModifiedTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-clihub/views/Containers(monitoringworkspace-clihub)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-clihub)\",\r\n \"name\": \"Containers(monitoringworkspace-clihub)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + }, + "New-AzMonitorLogAnalyticsSolution+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/SecurityCenterFree%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview+2": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/SecurityCenterFree%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview", + "Content": "{\n \"plan\": {\n \"name\": \"SecurityCenterFree(monitoringworkspace-k5foa9)\",\n \"product\": \"OMSGallery/SecurityCenterFree\",\n \"promotionCode\": \"\",\n \"publisher\": \"Microsoft\"\n },\n \"properties\": {\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\"\n },\n \"location\": \"eastus\"\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "434" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "2300b0a9-8612-458c-88d9-0fbc12503da5" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1188" ], + "x-ms-correlation-request-id": [ "d85f6e2a-6932-4140-bd5c-5b9924e580b3" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065716Z:d85f6e2a-6932-4140-bd5c-5b9924e580b3" ], + "Date": [ "Tue, 30 Jun 2020 06:57:16 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "951" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/SecurityCenterFree\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"lastModifiedTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"containedResources\": []\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"name\": \"SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + }, + "New-AzMonitorLogAnalyticsSolution+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Security%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview+3": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Security%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview", + "Content": "{\n \"plan\": {\n \"name\": \"Security(monitoringworkspace-k5foa9)\",\n \"product\": \"OMSGallery/Security\",\n \"promotionCode\": \"\",\n \"publisher\": \"Microsoft\"\n },\n \"properties\": {\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\"\n },\n \"location\": \"eastus\"\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "414" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "c1c24f06-72e3-4694-aec4-ad594bb24567" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1187" ], + "x-ms-correlation-request-id": [ "6a9a20e0-d2aa-46d6-8ea2-0550b227df08" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065720Z:6a9a20e0-d2aa-46d6-8ea2-0550b227df08" ], + "Date": [ "Tue, 30 Jun 2020 06:57:20 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1144" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Security(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Security\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"lastModifiedTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Security(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Security(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Security(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + }, + "New-AzMonitorLogAnalyticsSolution+[NoContext]+CreateExpanded+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Updates%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview+4": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Updates%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview", + "Content": "{\n \"plan\": {\n \"name\": \"Updates(monitoringworkspace-k5foa9)\",\n \"product\": \"OMSGallery/Updates\",\n \"promotionCode\": \"\",\n \"publisher\": \"Microsoft\"\n },\n \"properties\": {\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\"\n },\n \"location\": \"eastus\"\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "412" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "b5d2e131-79fe-4a19-9009-1938c590696a" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1186" ], + "x-ms-correlation-request-id": [ "1f20ffb4-55ab-4b74-9d7b-0b9b0c5a171c" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065723Z:1f20ffb4-55ab-4b74-9d7b-0b9b0c5a171c" ], + "Date": [ "Tue, 30 Jun 2020 06:57:23 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1139" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Updates(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Updates\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"lastModifiedTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Updates(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Updates(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Updates(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/test/New-AzMonitorLogAnalyticsSolution.Tests.ps1 b/src/MonitoringSolutions/test/New-AzMonitorLogAnalyticsSolution.Tests.ps1 new file mode 100644 index 000000000000..62883b1d52c8 --- /dev/null +++ b/src/MonitoringSolutions/test/New-AzMonitorLogAnalyticsSolution.Tests.ps1 @@ -0,0 +1,28 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'New-AzMonitorLogAnalyticsSolution.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'New-AzMonitorLogAnalyticsSolution' { + It 'CreateExpanded' { + $monitor = New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName $env.resourceGroup -Location $env.location -WorkspaceResourceId $env.workspaceResourceId02 + $monitor.ProvisioningState | Should -Be 'Succeeded' + + $monitor = New-AzMonitorLogAnalyticsSolution -Type SecurityCenterFree -ResourceGroupName $env.resourceGroup -Location $env.location -WorkspaceResourceId $env.workspaceResourceId01 + $monitor.ProvisioningState | Should -Be 'Succeeded' + + $monitor = New-AzMonitorLogAnalyticsSolution -Type Security -ResourceGroupName $env.resourceGroup -Location $env.location -WorkspaceResourceId $env.workspaceResourceId01 + $monitor.ProvisioningState | Should -Be 'Succeeded' + + $monitor = New-AzMonitorLogAnalyticsSolution -Type Updates -ResourceGroupName $env.resourceGroup -Location $env.location -WorkspaceResourceId $env.workspaceResourceId01 + $monitor.ProvisioningState | Should -Be 'Succeeded' + } +} diff --git a/src/MonitoringSolutions/test/Remove-AzMonitorLogAnalyticsSolution.Recording.json b/src/MonitoringSolutions/test/Remove-AzMonitorLogAnalyticsSolution.Recording.json new file mode 100644 index 000000000000..009577010a35 --- /dev/null +++ b/src/MonitoringSolutions/test/Remove-AzMonitorLogAnalyticsSolution.Recording.json @@ -0,0 +1,242 @@ +{ + "Remove-AzMonitorLogAnalyticsSolution+[NoContext]+Delete+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview", + "Content": "{\n \"plan\": {\n \"name\": \"Containers(monitoringworkspace-clihub)\",\n \"product\": \"OMSGallery/Containers\",\n \"promotionCode\": \"\",\n \"publisher\": \"Microsoft\"\n },\n \"properties\": {\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-clihub\"\n },\n \"location\": \"eastus\"\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "418" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "a23ab4e4-d4ab-4973-a130-9b372e91e284" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1185" ], + "x-ms-correlation-request-id": [ "4d0a2546-5a17-4412-ab14-71e41b7dcb00" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065724Z:4d0a2546-5a17-4412-ab14-71e41b7dcb00" ], + "Date": [ "Tue, 30 Jun 2020 06:57:24 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1154" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-clihub)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-clihub\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"lastModifiedTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-clihub/views/Containers(monitoringworkspace-clihub)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-clihub)\",\r\n \"name\": \"Containers(monitoringworkspace-clihub)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + }, + "Remove-AzMonitorLogAnalyticsSolution+[NoContext]+Delete+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview+2": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "13" ], + "x-ms-client-request-id": [ "09dcb65e-6c02-42d2-939f-5f2a8e48670f" ], + "CommandName": [ "Remove-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Remove-AzMonitorLogAnalyticsSolution_Delete" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "9ffd4e71-8ff8-4a8a-bfd3-50679db2f13e" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14999" ], + "x-ms-correlation-request-id": [ "cfee0cbe-cbd1-400d-8ee0-d4e51f960286" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065727Z:cfee0cbe-cbd1-400d-8ee0-d4e51f960286" ], + "Date": [ "Tue, 30 Jun 2020 06:57:27 GMT" ] + }, + "ContentHeaders": { + "Expires": [ "-1" ], + "Content-Length": [ "0" ] + }, + "Content": null + } + }, + "Remove-AzMonitorLogAnalyticsSolution+[NoContext]+Delete+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "14" ], + "x-ms-client-request-id": [ "636e6078-e3c1-40e2-97bd-4f485f6e1b4f" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "37672cb6-8c5c-4082-9f2f-14b8bacac561" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11990" ], + "x-ms-correlation-request-id": [ "d46a3b2e-a32f-4f56-834e-61d87481a41c" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065727Z:d46a3b2e-a32f-4f56-834e-61d87481a41c" ], + "Date": [ "Tue, 30 Jun 2020 06:57:27 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "4750" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"value\": [\r\n {\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n },\r\n {\r\n \"plan\": {\r\n \"name\": \"Security(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Security\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:19 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:19 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Security(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Security(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Security(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n },\r\n {\r\n \"plan\": {\r\n \"name\": \"SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/SecurityCenterFree\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:15 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:15 GMT\",\r\n \"containedResources\": []\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"name\": \"SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n },\r\n {\r\n \"plan\": {\r\n \"name\": \"Updates(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Updates\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:22 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:22 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Updates(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Updates(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Updates(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n }\r\n ]\r\n}" + } + }, + "Remove-AzMonitorLogAnalyticsSolution+[NoContext]+DeleteViaIdentity+$PUT+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "PUT", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-clihub%29?api-version=2015-11-01-preview", + "Content": "{\n \"plan\": {\n \"name\": \"Containers(monitoringworkspace-clihub)\",\n \"product\": \"OMSGallery/Containers\",\n \"promotionCode\": \"\",\n \"publisher\": \"Microsoft\"\n },\n \"properties\": {\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-clihub\"\n },\n \"location\": \"eastus\"\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "418" ] + } + }, + "Response": { + "StatusCode": 201, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "d4f9146c-25bc-445e-ab01-916781b6f4c7" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1184" ], + "x-ms-correlation-request-id": [ "d1b40f78-e203-4b2d-96a7-18a3684a7909" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065731Z:d1b40f78-e203-4b2d-96a7-18a3684a7909" ], + "Date": [ "Tue, 30 Jun 2020 06:57:30 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1154" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-clihub)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-clihub\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"lastModifiedTime\": \"Mon, 01 Jan 0001 00:00:00 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-clihub/views/Containers(monitoringworkspace-clihub)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-clihub)\",\r\n \"name\": \"Containers(monitoringworkspace-clihub)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n}" + } + }, + "Remove-AzMonitorLogAnalyticsSolution+[NoContext]+DeleteViaIdentity+$DELETE+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-clihub)?api-version=2015-11-01-preview+2": { + "Request": { + "Method": "DELETE", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-clihub)?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "16" ], + "x-ms-client-request-id": [ "5b49de74-f95f-416a-8f85-859b15f58a0b" ], + "CommandName": [ "Remove-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Remove-AzMonitorLogAnalyticsSolution_DeleteViaIdentity" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "a6245144-d914-440f-9923-bc641938f9bb" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-deletes": [ "14998" ], + "x-ms-correlation-request-id": [ "6e4487b0-36d8-407c-8aa0-b3d98cb2751f" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065733Z:6e4487b0-36d8-407c-8aa0-b3d98cb2751f" ], + "Date": [ "Tue, 30 Jun 2020 06:57:33 GMT" ] + }, + "ContentHeaders": { + "Expires": [ "-1" ], + "Content-Length": [ "0" ] + }, + "Content": null + } + }, + "Remove-AzMonitorLogAnalyticsSolution+[NoContext]+DeleteViaIdentity+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview+3": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "17" ], + "x-ms-client-request-id": [ "c7444b55-ff2c-4e7d-b7d4-134f7a32535b" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_List" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "cf88beef-df84-453b-9b7e-008258558440" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11989" ], + "x-ms-correlation-request-id": [ "76ae32e4-54c5-44b1-b3aa-e572607d8bac" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065734Z:76ae32e4-54c5-44b1-b3aa-e572607d8bac" ], + "Date": [ "Tue, 30 Jun 2020 06:57:33 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "4750" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"value\": [\r\n {\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n },\r\n {\r\n \"plan\": {\r\n \"name\": \"Security(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Security\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:19 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:19 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Security(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Security(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Security(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n },\r\n {\r\n \"plan\": {\r\n \"name\": \"SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/SecurityCenterFree\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:15 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:15 GMT\",\r\n \"containedResources\": []\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"name\": \"SecurityCenterFree(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n },\r\n {\r\n \"plan\": {\r\n \"name\": \"Updates(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Updates\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:22 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:22 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9/views/Updates(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Updates(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Updates(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\"\r\n }\r\n ]\r\n}" + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/test/Remove-AzMonitorLogAnalyticsSolution.Tests.ps1 b/src/MonitoringSolutions/test/Remove-AzMonitorLogAnalyticsSolution.Tests.ps1 new file mode 100644 index 000000000000..bd54d21d8f65 --- /dev/null +++ b/src/MonitoringSolutions/test/Remove-AzMonitorLogAnalyticsSolution.Tests.ps1 @@ -0,0 +1,28 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Remove-AzMonitorLogAnalyticsSolution.Recording.json' +$currentPath = $PSScriptRoot +while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent +} +. ($mockingPath | Select-Object -First 1).FullName + +Describe 'Remove-AzMonitorLogAnalyticsSolution' { + It 'Delete' { + $monitor = New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName $env.resourceGroup -Location $env.location -WorkspaceResourceId $env.workspaceResourceId02 + Remove-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup -Name $monitor.Name + $monitorList = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup + $monitorList.Name | Should -Not -Contain $monitor.Name + } + + It 'DeleteViaIdentity' { + $monitor = New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName $env.resourceGroup -Location $env.location -WorkspaceResourceId $env.workspaceResourceId02 + Remove-AzMonitorLogAnalyticsSolution -InputObject $monitor + $monitorList = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup + $monitorList.Name | Should -Not -Contain $monitor.Name + } +} diff --git a/src/MonitoringSolutions/test/Update-AzMonitorLogAnalyticsSolution.Recording.json b/src/MonitoringSolutions/test/Update-AzMonitorLogAnalyticsSolution.Recording.json new file mode 100644 index 000000000000..f80a62887c62 --- /dev/null +++ b/src/MonitoringSolutions/test/Update-AzMonitorLogAnalyticsSolution.Recording.json @@ -0,0 +1,118 @@ +{ + "Update-AzMonitorLogAnalyticsSolution+[NoContext]+UpdateExpanded+$PATCH+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "PATCH", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview", + "Content": "{\n \"tags\": {\n \"key02\": \"2\",\n \"key01\": \"1\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "54" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "ee1d3dba-0922-426c-89c8-2aa913904b0e" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1183" ], + "x-ms-correlation-request-id": [ "b33d8968-06ba-4dae-b8e7-d05e68644a12" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065736Z:b33d8968-06ba-4dae-b8e7-d05e68644a12" ], + "Date": [ "Tue, 30 Jun 2020 06:57:35 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1210" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\",\r\n \"tags\": {\r\n \"key02\": \"2\",\r\n \"key01\": \"1\"\r\n }\r\n}" + } + }, + "Update-AzMonitorLogAnalyticsSolution+[NoContext]+UpdateViaIdentityExpanded+$GET+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview+1": { + "Request": { + "Method": "GET", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers%28monitoringworkspace-k5foa9%29?api-version=2015-11-01-preview", + "Content": null, + "Headers": { + "x-ms-unique-id": [ "19" ], + "x-ms-client-request-id": [ "650628cc-3fcc-40bc-80cf-f78437c07bc0" ], + "CommandName": [ "Get-AzMonitorLogAnalyticsSolution" ], + "FullCommandName": [ "Get-AzMonitorLogAnalyticsSolution_Get" ], + "ParameterSetName": [ "__AllParameterSets" ], + "User-Agent": [ "AzurePowershell/Az4.0.0-preview" ], + "Authorization": [ "[Filtered]" ] + }, + "ContentHeaders": { + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "d24ef9a7-c811-4209-b8f9-1f867b2889ac" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-reads": [ "11988" ], + "x-ms-correlation-request-id": [ "70dc5f3e-469b-416b-8e94-0121ba263c76" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065736Z:70dc5f3e-469b-416b-8e94-0121ba263c76" ], + "Date": [ "Tue, 30 Jun 2020 06:57:36 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1210" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:34 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\",\r\n \"tags\": {\r\n \"key02\": \"2\",\r\n \"key01\": \"1\"\r\n }\r\n}" + } + }, + "Update-AzMonitorLogAnalyticsSolution+[NoContext]+UpdateViaIdentityExpanded+$PATCH+https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)?api-version=2015-11-01-preview+2": { + "Request": { + "Method": "PATCH", + "RequestUri": "https://management.azure.com/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)?api-version=2015-11-01-preview", + "Content": "{\n \"tags\": {\n \"key01\": \"1\",\n \"key03\": \"3\",\n \"key02\": \"2\"\n }\n}", + "Headers": { + }, + "ContentHeaders": { + "Content-Type": [ "application/json" ], + "Content-Length": [ "72" ] + } + }, + "Response": { + "StatusCode": 200, + "Headers": { + "Cache-Control": [ "no-cache" ], + "Pragma": [ "no-cache" ], + "X-AMS-APIVersion": [ "WebAPI1.0" ], + "CacheControl": [ "no-cache" ], + "x-ms-request-id": [ "d004f320-ed3d-42fc-bef3-1ef9f7a6eb08" ], + "Strict-Transport-Security": [ "max-age=31536000; includeSubDomains" ], + "X-Content-Type-Options": [ "nosniff" ], + "Server": [ "Microsoft-IIS/10.0", "Microsoft-IIS/10.0" ], + "X-Powered-By": [ "ASP.NET", "ASP.NET" ], + "x-ms-ratelimit-remaining-subscription-writes": [ "1182" ], + "x-ms-correlation-request-id": [ "c5f2acb3-7c9a-4b10-8cd5-ac3f5716f073" ], + "x-ms-routing-request-id": [ "SOUTHEASTASIA:20200630T065738Z:c5f2acb3-7c9a-4b10-8cd5-ac3f5716f073" ], + "Date": [ "Tue, 30 Jun 2020 06:57:38 GMT" ] + }, + "ContentHeaders": { + "Content-Length": [ "1229" ], + "Content-Type": [ "application/json; charset=utf-8" ], + "Expires": [ "-1" ] + }, + "Content": "{\r\n \"plan\": {\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"publisher\": \"Microsoft\",\r\n \"promotionCode\": \"\",\r\n \"product\": \"OMSGallery/Containers\"\r\n },\r\n \"properties\": {\r\n \"workspaceResourceId\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9\",\r\n \"provisioningState\": \"Succeeded\",\r\n \"creationTime\": \"Tue, 30 Jun 2020 06:57:03 GMT\",\r\n \"lastModifiedTime\": \"Tue, 30 Jun 2020 06:57:34 GMT\",\r\n \"containedResources\": [\r\n \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationalInsights/workspaces/monitoringworkspace-k5foa9/views/Containers(monitoringworkspace-k5foa9)\"\r\n ]\r\n },\r\n \"id\": \"/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/Microsoft.OperationsManagement/solutions/Containers(monitoringworkspace-k5foa9)\",\r\n \"name\": \"Containers(monitoringworkspace-k5foa9)\",\r\n \"type\": \"Microsoft.OperationsManagement/solutions\",\r\n \"location\": \"East US\",\r\n \"tags\": {\r\n \"key01\": \"1\",\r\n \"key03\": \"3\",\r\n \"key02\": \"2\"\r\n }\r\n}" + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/test/Update-AzMonitorLogAnalyticsSolution.Tests.ps1 b/src/MonitoringSolutions/test/Update-AzMonitorLogAnalyticsSolution.Tests.ps1 new file mode 100644 index 000000000000..9d63f1f3b306 --- /dev/null +++ b/src/MonitoringSolutions/test/Update-AzMonitorLogAnalyticsSolution.Tests.ps1 @@ -0,0 +1,27 @@ +$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' +if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' +} +. ($loadEnvPath) +$TestRecordingFile = Join-Path $PSScriptRoot 'Update-AzMonitorLogAnalyticsSolution.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 'Update-AzMonitorLogAnalyticsSolution' { + It 'UpdateExpanded' { + $tag = @{'key01' = 1; 'key02' = 2} + $monitor = Update-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup -Name $env.monitorName01 -Tag $tag + $monitor.Tag.Count | Should -Be 2 + } + + It 'UpdateViaIdentityExpanded' { + $tag = @{'key01' = 1; 'key02' = 2; 'key03' = 3} + $monitor = Get-AzMonitorLogAnalyticsSolution -ResourceGroupName $env.resourceGroup -Name $env.monitorName01 + $newMonitor = Update-AzMonitorLogAnalyticsSolution -InputObject $monitor -Tag $tag + $newMonitor.Tag.Count | Should -Be 3 + } +} diff --git a/src/MonitoringSolutions/test/deployment-templates/operational-insightsworkspace/parameters.json b/src/MonitoringSolutions/test/deployment-templates/operational-insightsworkspace/parameters.json new file mode 100644 index 000000000000..abd6820e0930 --- /dev/null +++ b/src/MonitoringSolutions/test/deployment-templates/operational-insightsworkspace/parameters.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "workspaces_yemingmonitor_name": { + "value": "lucasmonitor" + } + } +} \ No newline at end of file diff --git a/src/MonitoringSolutions/test/deployment-templates/operational-insightsworkspace/template.json b/src/MonitoringSolutions/test/deployment-templates/operational-insightsworkspace/template.json new file mode 100644 index 000000000000..06bbbc910147 --- /dev/null +++ b/src/MonitoringSolutions/test/deployment-templates/operational-insightsworkspace/template.json @@ -0,0 +1,574 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "workspaces_yemingmonitor_name": { + "defaultValue": "lucasmonitor", + "type": "String" + } + }, + "variables": {}, + "resources": [ + { + "type": "microsoft.operationalinsights/workspaces", + "apiVersion": "2020-03-01-preview", + "name": "[parameters('workspaces_yemingmonitor_name')]", + "location": "westus2", + "properties": { + "provisioningState": "Succeeded", + "sku": { + "name": "pergb2018" + }, + "retentionInDays": 30, + "publicNetworkAccessForIngestion": "Enabled", + "publicNetworkAccessForQuery": "Enabled" + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_General|AlphabeticallySortedComputers')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All Computers with their most recent data", + "category": "General Exploration", + "query": "search not(ObjectName == \"Advisor Metrics\" or ObjectName == \"ManagedSpace\") | summarize AggregatedValue = max(TimeGenerated) by Computer | limit 500000 | sort by Computer asc\r\n// Oql: NOT(ObjectName=\"Advisor Metrics\" OR ObjectName=ManagedSpace) | measure max(TimeGenerated) by Computer | top 500000 | Sort Computer // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_General|dataPointsPerManagementGroup')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Which Management Group is generating the most data points?", + "category": "General Exploration", + "query": "search * | summarize AggregatedValue = count() by ManagementGroupName\r\n// Oql: * | Measure count() by ManagementGroupName // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_General|dataTypeDistribution')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Distribution of data Types", + "category": "General Exploration", + "query": "search * | extend Type = $table | summarize AggregatedValue = count() by Type\r\n// Oql: * | Measure count() by Type // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_General|StaleComputers')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Stale Computers (data older than 24 hours)", + "category": "General Exploration", + "query": "search not(ObjectName == \"Advisor Metrics\" or ObjectName == \"ManagedSpace\") | summarize lastdata = max(TimeGenerated) by Computer | limit 500000 | where lastdata < ago(24h)\r\n// Oql: NOT(ObjectName=\"Advisor Metrics\" OR ObjectName=ManagedSpace) | measure max(TimeGenerated) as lastdata by Computer | top 500000 | where lastdata < NOW-24HOURS // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|AllEvents')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All Events", + "category": "Log Management", + "query": "Event | sort by TimeGenerated desc\r\n// Oql: Type=Event // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|AllSyslog')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All Syslogs", + "category": "Log Management", + "query": "Syslog | sort by TimeGenerated desc\r\n// Oql: Type=Syslog // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|AllSyslogByFacility')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All Syslog Records grouped by Facility", + "category": "Log Management", + "query": "Syslog | summarize AggregatedValue = count() by Facility\r\n// Oql: Type=Syslog | Measure count() by Facility // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|AllSyslogByProcessName')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All Syslog Records grouped by ProcessName", + "category": "Log Management", + "query": "Syslog | summarize AggregatedValue = count() by ProcessName\r\n// Oql: Type=Syslog | Measure count() by ProcessName // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|AllSyslogsWithErrors')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All Syslog Records with Errors", + "category": "Log Management", + "query": "Syslog | where SeverityLevel == \"error\" | sort by TimeGenerated desc\r\n// Oql: Type=Syslog SeverityLevel=error // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|AverageHTTPRequestTimeByClientIPAddress')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Average HTTP Request time by Client IP Address", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = avg(TimeTaken) by cIP\r\n// Oql: Type=W3CIISLog | Measure Avg(TimeTaken) by cIP // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|AverageHTTPRequestTimeHTTPMethod')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Average HTTP Request time by HTTP Method", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = avg(TimeTaken) by csMethod\r\n// Oql: Type=W3CIISLog | Measure Avg(TimeTaken) by csMethod // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|CountIISLogEntriesClientIPAddress')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of IIS Log Entries by Client IP Address", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by cIP\r\n// Oql: Type=W3CIISLog | Measure count() by cIP // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|CountIISLogEntriesHTTPRequestMethod')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of IIS Log Entries by HTTP Request Method", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by csMethod\r\n// Oql: Type=W3CIISLog | Measure count() by csMethod // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|CountIISLogEntriesHTTPUserAgent')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of IIS Log Entries by HTTP User Agent", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by csUserAgent\r\n// Oql: Type=W3CIISLog | Measure count() by csUserAgent // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|CountOfIISLogEntriesByHostRequestedByClient')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of IIS Log Entries by Host requested by client", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by csHost\r\n// Oql: Type=W3CIISLog | Measure count() by csHost // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|CountOfIISLogEntriesByURLForHost')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of IIS Log Entries by URL for the host \"www.contoso.com\" (replace with your own)", + "category": "Log Management", + "query": "search csHost == \"www.contoso.com\" | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by csUriStem\r\n// Oql: Type=W3CIISLog csHost=\"www.contoso.com\" | Measure count() by csUriStem // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|CountOfIISLogEntriesByURLRequestedByClient')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of IIS Log Entries by URL requested by client (without query strings)", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by csUriStem\r\n// Oql: Type=W3CIISLog | Measure count() by csUriStem // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|CountOfWarningEvents')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of Events with level \"Warning\" grouped by Event ID", + "category": "Log Management", + "query": "Event | where EventLevelName == \"warning\" | summarize AggregatedValue = count() by EventID\r\n// Oql: Type=Event EventLevelName=warning | Measure count() by EventID // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|DisplayBreakdownRespondCodes')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Shows breakdown of response codes", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by scStatus\r\n// Oql: Type=W3CIISLog | Measure count() by scStatus // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|EventsByEventLog')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of Events grouped by Event Log", + "category": "Log Management", + "query": "Event | summarize AggregatedValue = count() by EventLog\r\n// Oql: Type=Event | Measure count() by EventLog // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|EventsByEventsID')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of Events grouped by Event ID", + "category": "Log Management", + "query": "Event | summarize AggregatedValue = count() by EventID\r\n// Oql: Type=Event | Measure count() by EventID // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|EventsByEventSource')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of Events grouped by Event Source", + "category": "Log Management", + "query": "Event | summarize AggregatedValue = count() by Source\r\n// Oql: Type=Event | Measure count() by Source // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|EventsInOMBetween2000to3000')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Events in the Operations Manager Event Log whose Event ID is in the range between 2000 and 3000", + "category": "Log Management", + "query": "Event | where EventLog == \"Operations Manager\" and EventID >= 2000 and EventID <= 3000 | sort by TimeGenerated desc\r\n// Oql: Type=Event EventLog=\"Operations Manager\" EventID:[2000..3000] // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|EventsWithStartedinEventID')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Count of Events containing the word \"started\" grouped by EventID", + "category": "Log Management", + "query": "search in (Event) \"started\" | summarize AggregatedValue = count() by EventID\r\n// Oql: Type=Event \"started\" | Measure count() by EventID // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|FindMaximumTimeTakenForEachPage')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Find the maximum time taken for each page", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = max(TimeTaken) by csUriStem\r\n// Oql: Type=W3CIISLog | Measure Max(TimeTaken) by csUriStem // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|IISLogEntriesForClientIP')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "IIS Log Entries for a specific client IP Address (replace with your own)", + "category": "Log Management", + "query": "search cIP == \"192.168.0.1\" | extend Type = $table | where Type == W3CIISLog | sort by TimeGenerated desc | project csUriStem, scBytes, csBytes, TimeTaken, scStatus\r\n// Oql: Type=W3CIISLog cIP=\"192.168.0.1\" | Select csUriStem,scBytes,csBytes,TimeTaken,scStatus // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|ListAllIISLogEntries')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All IIS Log Entries", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | sort by TimeGenerated desc\r\n// Oql: Type=W3CIISLog // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|NoOfConnectionsToOMSDKService')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "How many connections to Operations Manager's SDK service by day", + "category": "Log Management", + "query": "Event | where EventID == 26328 and EventLog == \"Operations Manager\" | summarize AggregatedValue = count() by bin(TimeGenerated, 1d) | sort by TimeGenerated desc\r\n// Oql: Type=Event EventID=26328 EventLog=\"Operations Manager\" | Measure count() interval 1DAY // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|ServerRestartTime')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "When did my servers initiate restart?", + "category": "Log Management", + "query": "search in (Event) \"shutdown\" and EventLog == \"System\" and Source == \"User32\" and EventID == 1074 | sort by TimeGenerated desc | project TimeGenerated, Computer\r\n// Oql: shutdown Type=Event EventLog=System Source=User32 EventID=1074 | Select TimeGenerated,Computer // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|Show404PagesList')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Shows which pages people are getting a 404 for", + "category": "Log Management", + "query": "search scStatus == 404 | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by csUriStem\r\n// Oql: Type=W3CIISLog scStatus=404 | Measure count() by csUriStem // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|ShowServersThrowingInternalServerError')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Shows servers that are throwing internal server error", + "category": "Log Management", + "query": "search scStatus == 500 | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = count() by sComputerName\r\n// Oql: Type=W3CIISLog scStatus=500 | Measure count() by sComputerName // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|TotalBytesReceivedByEachAzureRoleInstance')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Total Bytes received by each Azure Role Instance", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = sum(csBytes) by RoleInstance\r\n// Oql: Type=W3CIISLog | Measure Sum(csBytes) by RoleInstance // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|TotalBytesReceivedByEachIISComputer')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Total Bytes received by each IIS Computer", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = sum(csBytes) by Computer | limit 500000\r\n// Oql: Type=W3CIISLog | Measure Sum(csBytes) by Computer | top 500000 // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|TotalBytesRespondedToClientsByClientIPAddress')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Total Bytes responded back to clients by Client IP Address", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = sum(scBytes) by cIP\r\n// Oql: Type=W3CIISLog | Measure Sum(scBytes) by cIP // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|TotalBytesRespondedToClientsByEachIISServerIPAddress')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Total Bytes responded back to clients by each IIS ServerIP Address", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = sum(scBytes) by sIP\r\n// Oql: Type=W3CIISLog | Measure Sum(scBytes) by sIP // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|TotalBytesSentByClientIPAddress')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Total Bytes sent by Client IP Address", + "category": "Log Management", + "query": "search * | extend Type = $table | where Type == W3CIISLog | summarize AggregatedValue = sum(csBytes) by cIP\r\n// Oql: Type=W3CIISLog | Measure Sum(csBytes) by cIP // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PEF: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|WarningEvents')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "All Events with level \"Warning\"", + "category": "Log Management", + "query": "Event | where EventLevelName == \"warning\" | sort by TimeGenerated desc\r\n// Oql: Type=Event EventLevelName=warning // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|WindowsFireawallPolicySettingsChanged')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "Windows Firewall Policy settings have changed", + "category": "Log Management", + "query": "Event | where EventLog == \"Microsoft-Windows-Windows Firewall With Advanced Security/Firewall\" and EventID == 2008 | sort by TimeGenerated desc\r\n// Oql: Type=Event EventLog=\"Microsoft-Windows-Windows Firewall With Advanced Security/Firewall\" EventID=2008 // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + }, + { + "type": "Microsoft.OperationalInsights/workspaces/savedSearches", + "apiVersion": "2020-03-01-preview", + "name": "[concat(parameters('workspaces_yemingmonitor_name'), '/LogManagement(', parameters('workspaces_yemingmonitor_name'), ')_LogManagement|WindowsFireawallPolicySettingsChangedByMachines')]", + "dependsOn": [ + "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaces_yemingmonitor_name'))]" + ], + "properties": { + "displayName": "On which machines and how many times have Windows Firewall Policy settings changed", + "category": "Log Management", + "query": "Event | where EventLog == \"Microsoft-Windows-Windows Firewall With Advanced Security/Firewall\" and EventID == 2008 | summarize AggregatedValue = count() by Computer | limit 500000\r\n// Oql: Type=Event EventLog=\"Microsoft-Windows-Windows Firewall With Advanced Security/Firewall\" EventID=2008 | measure count() by Computer | top 500000 // Args: {OQ: True; WorkspaceId: 00000000-0000-0000-0000-000000000000} // Settings: {PTT: True; SortI: True; SortF: True} // Version: 0.1.122", + "version": 2 + } + } + ] +} \ No newline at end of file diff --git a/src/MonitoringSolutions/test/env.json b/src/MonitoringSolutions/test/env.json new file mode 100644 index 000000000000..e6b590146012 --- /dev/null +++ b/src/MonitoringSolutions/test/env.json @@ -0,0 +1,9 @@ +{ + "monitorName01": "Containers(monitoringworkspace-k5foa9)", + "location": "eastus", + "workspaceResourceId02": "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-clihub", + "resourceGroup": "monitoringsolutions-rg-ol9km3", + "Tenant": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "workspaceResourceId01": "/subscriptions/9e223dbe-3399-4e19-88eb-0975f02ac87f/resourcegroups/monitoringsolutions-rg-ol9km3/providers/microsoft.operationalinsights/workspaces/monitoringworkspace-k5foa9", + "SubscriptionId": "9e223dbe-3399-4e19-88eb-0975f02ac87f" +} diff --git a/src/MonitoringSolutions/test/loadEnv.ps1 b/src/MonitoringSolutions/test/loadEnv.ps1 new file mode 100644 index 000000000000..c4ebf2e8310c --- /dev/null +++ b/src/MonitoringSolutions/test/loadEnv.ps1 @@ -0,0 +1,28 @@ +# ---------------------------------------------------------------------------------- +# +# Copyright Microsoft Corporation +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:SubscriptionId"=$env.SubscriptionId; "*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/src/MonitoringSolutions/test/readme.md b/src/MonitoringSolutions/test/readme.md new file mode 100644 index 000000000000..7c752b4c8c43 --- /dev/null +++ b/src/MonitoringSolutions/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/MonitoringSolutions/test/utils.ps1 b/src/MonitoringSolutions/test/utils.ps1 new file mode 100644 index 000000000000..291637f81bbe --- /dev/null +++ b/src/MonitoringSolutions/test/utils.ps1 @@ -0,0 +1,61 @@ +function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +$env = @{} +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + Write-Host -ForegroundColor Yellow "Required Az.OperationalInsights, please check if Az.OperationalInsights installed" + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + $env.location = 'eastus' + # For any resources you created for test, you should add it to $env here. + #Generate some random strings for use in the test. + $rstr1 = RandomString -allChars $false -len 6 + $rstr2 = RandomString -allChars $false -len 6 + $rstr3 = RandomString -allChars $false -len 6 + + #Create the test group. + Write-Host -ForegroundColor Green 'Create test group' + $resourceGroup = 'monitoringsolutions-rg-' + $rstr1 + New-AzResourceGroup -Name $resourceGroup -Location $env.location + $null = $env.Add('resourceGroup', $resourceGroup) + Write-Host -ForegroundColor Green 'The test group created successfully' + + # Deploy operational insights workspace + Write-Host -ForegroundColor Green 'Deploying operational insights workspace' + $workspacesName01 = 'monitoringworkspace-' + (RandomString -allChars $false -len 6) + $workspacesName02 = 'monitoringworkspace-' + (RandomString -allChars $false -len 6) + <# Deploy failed, azure portal responsed error message: "statusMessage": "{\"error\":{\"code\":\"InvalidRequestContent\",\"message\":\"The request content was invalid and could not be deserialized: 'Error converting value \\\"insights-jxvq9o\\\" to type 'Microsoft.WindowsAzure.ResourceStack.Frontdoor.Data.Definitions.DeploymentParameterDefinition'. Path 'properties.parameters.workspaces_name', line 5, position 42.'.\"}}", + $workspacesParam = Get-Content .\test\deployment-templates\operational-insightsworkspace\parameters.json | ConvertFrom-Json + $workspacesParam.parameters.workspaces_yemingmonitor_name = 'lucasmonitor' + set-content -Path .\test\deployment-templates\operational-insightsworkspace\parameters.json -Value (ConvertTo-Json $workspacesParam) + New-AzDeployment -Mode Incremental -TemplateFile .\test\deployment-templates\operational-insightsworkspace\template.json -TemplateParameterFile .\test\deployment-templates\operational-insightsworkspace\parameters.json -ResourceGroupName $env.resourceGroup + #> + $workspace01 = New-AzOperationalInsightsWorkspace -ResourceGroupName $env.resourceGroup -Name $workspacesName01 -Location $env.location -Sku "Standard" + $workspace02 = New-AzOperationalInsightsWorkspace -ResourceGroupName $env.resourceGroup -Name $workspacesName02 -Location $env.location -Sku "Standard" + $null = $env.Add('workspaceResourceId01', $workspace01.ResourceId) + $null = $env.Add('workspaceResourceId02', $workspace02.ResourceId) + Write-Host -ForegroundColor Green 'The operational insights workspace deployed successfully' + + # Create monitor log analytics for test. + Write-Host -ForegroundColor Green 'create monitor log analytics' + $monitor = New-AzMonitorLogAnalyticsSolution -Type Containers -ResourceGroupName $env.resourceGroup -Location $env.location -WorkspaceResourceId $env.workspaceResourceId01 + $env.Add('monitorName01', $monitor.Name) + Write-Host -ForegroundColor Green 'The monitor log analytics created successfully' + + $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 + Remove-AzResourceGroup -Name $env.resourceGroup +} + diff --git a/tools/CreateMappings_rules.json b/tools/CreateMappings_rules.json index 75736acc3fac..2780db7c4a4e 100644 --- a/tools/CreateMappings_rules.json +++ b/tools/CreateMappings_rules.json @@ -177,5 +177,10 @@ { "regex": "Functions", "alias": "Functions" }, { "regex": "DesktopVirtualization", "alias": "DesktopVirtualization" }, { "regex": "AppConfiguration", "alias": "App Configuration" }, - { "regex": "StackEdge", "alias": "Stack Edge" } + { "regex": "HanaOnAzure", "alias": "SAP HANA on Azure" }, + { "regex": "CustomProviders", "alias": "Custom Resource Providers" }, + { "regex": "MonitoringSolutions", "alias": "Monitoring Solutions" }, + { "regex": "StackEdge", "alias": "Stack Edge" }, + { "regex": "ConnectedKubernetes", "alias": "Connected Kubernetes" }, + { "regex": "KubernetesConfiguration", "alias": "Kubernetes Configuration" } ] diff --git a/tools/GenerateHelp.ps1 b/tools/GenerateHelp.ps1 index 55078cbdb279..8ad8baeb7cd5 100644 --- a/tools/GenerateHelp.ps1 +++ b/tools/GenerateHelp.ps1 @@ -81,13 +81,18 @@ if ($ValidateMarkdownHelp) # We need to define new version of module instead of hardcode here $NewModules = @("Az.AppConfiguration", "Az.Blockchain", + "Az.ConnectedKubernetes", + "Az.CustomProviders", "Az.Databricks", "Az.DesktopVirtualization", "Az.Functions", + "Az.HanaOnAzure", "Az.ImageBuilder", "Az.ImportExport", + "Az.KubernetesConfiguration", "Az.Kusto", "Az.MariaDb", + "Az.MonitoringSolutions", "Az.MySql", "Az.Portal", "Az.PostgreSql", diff --git a/tools/SecurityTools/CredScanSuppressions.json b/tools/SecurityTools/CredScanSuppressions.json index 920484d54e3f..755ebf104ce8 100644 --- a/tools/SecurityTools/CredScanSuppressions.json +++ b/tools/SecurityTools/CredScanSuppressions.json @@ -1060,6 +1060,26 @@ { "file": "src\\Attestation\\Attestation.Test\\SessionRecords\\Microsoft.Azure.Commands.Attestation.Test.ScenarioTests.AttestationPolicySignerTests\\TestAddAttestationPolicySigner.json", "_justification": "The resources are being deleted after the test run in Record mode." + }, + { + "file": "src\\HanaOnAzure\\test\\env.json", + "_justification": "Test resource is deleted" + }, + { + "file": "src\\HanaOnAzure\\exports\\New-AzSapMonitorProviderInstance.ps1", + "_justification": "Test resource is deleted" + }, + { + "file": "src\\HanaOnAzure\\exports\\ProxyCmdletDefinitions.ps1", + "_justification": "Test resource is deleted" + }, + { + "file": "src\\HanaOnAzure\\internal\\New-AzSapMonitorProviderInstance.ps1", + "_justification": "Test resource is deleted" + }, + { + "file": "src\\HanaOnAzure\\internal\\ProxyCmdletDefinitions.ps1", + "_justification": "Test resource is deleted" } ] }